transformers icon indicating copy to clipboard operation
transformers copied to clipboard

Remote code is copied into HF_MODULES_CACHE non-atomically, so a concurrent process can import a truncated module

Open hivaze opened this issue 2 weeks ago • 6 comments

get_cached_module_file copies remote code into HF_MODULES_CACHE with a plain shutil.copyfile behind an exists() check (dynamic_module_utils.py around 482-483 on main, the hub-cache branch). When several processes load the same trust_remote_code model at once (every rank of a torchrun job on a shared cache), a process that arrives while another is mid-copy sees the file, skips its own copy, and imports a truncated module. That shows up as a NameError or SyntaxError on some ranks, sometimes.

The repro below slows one copy down to make the window visible. A second caller returns while the file holds 138,906 of 277,812 bytes, and importing it fails with NameError: name 'X' is not defined. CPU, offline, main (5.24.0.dev0).

Repro
import os, shutil, tempfile, threading, time
root = tempfile.mkdtemp(prefix="dmrace-")
os.environ.update(HF_HOME=root + "/hf", HF_MODULES_CACHE=root + "/modules", HF_HUB_OFFLINE="1")
import transformers.dynamic_module_utils as dmu

commit = "a" * 40
snap = f"{root}/hf/hub/models--org--remote/snapshots/{commit}"
os.makedirs(snap); os.makedirs(f"{root}/hf/hub/models--org--remote/refs")
open(f"{root}/hf/hub/models--org--remote/refs/main", "w").write(commit)
body = "import torch\n" + "\n".join(f"X{i} = {i}" for i in range(20000)) + "\nVALUE = 'complete'\n"
open(f"{snap}/modeling_remote.py", "w").write(body)

real_copy = shutil.copyfile
def slow_copy(src, dst, *a, **k):  # one process's copy is slow, as on a busy shared filesystem
    data = open(src, "rb").read()
    with open(dst, "wb") as f:
        f.write(data[: len(data) // 2]); f.flush(); time.sleep(1.5); f.write(data[len(data) // 2:])
    return dst

def first():
    dmu.shutil.copyfile = slow_copy
    dmu.get_cached_module_file("org/remote", "modeling_remote.py")

t = threading.Thread(target=first); t.start()
find = lambda: [os.path.join(d, f) for d, _, fs in os.walk(root + "/modules") for f in fs if f == "modeling_remote.py"]
while not find():
    time.sleep(0.05)
dmu.shutil.copyfile = real_copy  # the second process finds the file and skips its copy
dmu.get_cached_module_file("org/remote", "modeling_remote.py")
print("complete" if "VALUE = 'complete'" in open(find()[0]).read() else "TRUNCATED")
t.join()

This is not the hub download race fixed in huggingface_hub 0.24.7 (#27421); it's the copy into the modules cache. Copying to a temporary name in the same directory and os.replace-ing it into place would close it. I can send that PR.

Found while launching multi-rank jobs in Halo.

hivaze avatar Nov 16 '26 18:11 hivaze

cc @Cyrilvallez for model loading

Rocketknight1 avatar Nov 17 '26 12:11 Rocketknight1

There is also a persistent-cache case worth covering in the eventual fix: if the copying process exits after publishing a partial destination, later independent processes continue to accept that file through the exists() check. The failure survives the original writer.

An offline, event-controlled test with separate native processes writes 277,799 of 277,842 bytes, then exits with code 73. Both a subsequent reader and a later fresh reader get NameError: name 'UNFINISHED_CONSTANT' is not defined through get_class_in_module. If the original writer finishes normally, the later reader succeeds instead. An isolated same-directory temporary-file/os.replace intervention passes both concurrent and interrupted-writer cases. This is a publication experiment, not a proposed production patch or a cleanup/relative-import qualification.

Tested with Transformers 5.22.2 and huggingface_hub 2.4.0; the entire imported dynamic_module_utils.py is byte-identical to blob 7262c986425bd265110dd3e4a17540c9e86b3691 at main 487208b35c13834746b49a1c3c6dec61b04a8ebc. No network, model or GPU was used. Could your regression also include an interrupted writer followed by a fresh loader, so recovery is not tested only after a successful copy?

Exact process-level reproducer and results

Save the script below as cache_race.py. From the pinned source checkout, using an existing environment with the stated dependencies:

TF_SOURCE_FILE="$PWD/src/transformers/dynamic_module_utils.py" \
CUDA_VISIBLE_DEVICES="" .venv/bin/python cache_race.py
"""Deterministic process-level remote-module publication regression.

Offline synthetic Hub snapshot, genuine Transformers cache/import entry points.
The atomic arm is an explicitly isolated copy intervention, not an upstream fix.
No model, remote code, network, GPU or production cache is used.
"""
import ast
import hashlib
import json
import multiprocessing as mp
import os
from pathlib import Path
import tempfile
import traceback

os.environ.update(OMP_NUM_THREADS='1', OPENBLAS_NUM_THREADS='1', MKL_NUM_THREADS='1',
                  NUMEXPR_NUM_THREADS='1', TOKENIZERS_PARALLELISM='false')

COMMIT = 'a' * 40
REPO = 'org/remote'


def child(kind, root, mode, paused, release, results):
    root = Path(root)
    os.environ.update(HF_HOME=str(root/'hf'), HF_MODULES_CACHE=str(root/'modules'),
                      HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1',
                      HF_HUB_DISABLE_TELEMETRY='1', TOKENIZERS_PARALLELISM='false')
    try:
        import transformers
        import transformers.dynamic_module_utils as dmu
        source = root/'hf/hub/models--org--remote/snapshots'/COMMIT/'modeling_remote.py'
        expected = source.read_bytes()
        original = dmu.shutil.copyfile
        if kind == 'writer':
            def blocked_copy(src, dst, *args, **kwargs):
                if Path(src) != source:
                    return original(src, dst, *args, **kwargs)
                data = Path(src).read_bytes()
                cut = data.index(b'UNFINISHED_CONSTANT') + len(b'UNFINISHED_CONSTANT')
                destination = Path(dst)
                temporary = None
                if mode.startswith('atomic'):
                    f = tempfile.NamedTemporaryFile(dir=destination.parent,
                                                   prefix='.module-', delete=False)
                    temporary = Path(f.name)
                else:
                    f = destination.open('wb')
                with f:
                    f.write(data[:cut]); f.flush(); os.fsync(f.fileno())
                    paused.set()
                    if mode.endswith('interrupted'):
                        os._exit(73)
                    assert release.wait(45), 'Parent did not release controlled copy'
                    f.write(data[cut:]); f.flush()
                if temporary is not None:
                    os.replace(temporary, destination)
                return dst
            dmu.shutil.copyfile = blocked_copy
        cached = dmu.get_cached_module_file(REPO, 'modeling_remote.py',
                                            cache_dir=str(root/'hf/hub'),
                                            revision=COMMIT, local_files_only=True)
        path = root/'modules'/cached
        record = dict(kind=kind, mode=mode, returned=True,
                      published_bytes=path.stat().st_size, expected_bytes=len(expected),
                      byte_exact=path.read_bytes()==expected,
                      native_module_sha256=hashlib.sha256(Path(dmu.__file__).read_bytes()).hexdigest(),
                      transformers_version=transformers.__version__)
        try:
            cls = dmu.get_class_in_module('Cached', cached)
            record.update(import_ok=True, value=cls.value)
        except Exception as exc:
            record.update(import_ok=False, error_type=type(exc).__name__, error=str(exc))
        results.put(record)
    except Exception:
        results.put(dict(kind=kind, fatal=traceback.format_exc()))
        raise


def one_case(ctx, mode):
    with tempfile.TemporaryDirectory(prefix='cmp-tf50843-') as temp:
        root = Path(temp)
        snapshot = root/'hf/hub/models--org--remote/snapshots'/COMMIT
        snapshot.mkdir(parents=True)
        # A cut after this identifier is valid Python that raises NameError;
        # the complete source is an assignment followed by the expected class.
        body = ''.join(f'P{i} = {i}\n' for i in range(20000))
        body += "UNFINISHED_CONSTANT = 17\nclass Cached:\n    value = 'complete'\n"
        (snapshot/'modeling_remote.py').write_text(body)
        paused, release, results = ctx.Event(), ctx.Event(), ctx.Queue()
        writer = ctx.Process(target=child, args=('writer', temp, mode, paused, release, results))
        processes = [writer]
        try:
            writer.start(); assert paused.wait(45), 'Writer did not reach controlled window'
            interrupted = mode.endswith('interrupted')
            if interrupted:
                writer.join(10); assert writer.exitcode == 73
            reader = ctx.Process(target=child, args=('reader', temp, mode, paused, release, results))
            processes.append(reader); reader.start(); reader.join(45)
            assert reader.exitcode == 0, ('reader', reader.exitcode)
            during = results.get(timeout=10); assert during['kind']=='reader' and 'fatal' not in during
            if mode.startswith('plain'):
                assert not during['byte_exact'] and not during['import_ok']
                assert during['error_type']=='NameError' and 'UNFINISHED_CONSTANT' in during['error']
            else:
                assert during['byte_exact'] and during['import_ok'] and during['value']=='complete'
            release.set()
            if not interrupted:
                writer.join(45); assert writer.exitcode == 0
                completed = results.get(timeout=10)
                assert completed['kind']=='writer' and completed['byte_exact'] and completed['import_ok']
            # Independent fresh importer after the original writer has exited.
            late = ctx.Process(target=child, args=('late_reader', temp, mode, paused, release, results))
            processes.append(late); late.start(); late.join(45)
            assert late.exitcode == 0
            after = results.get(timeout=10); assert after['kind']=='late_reader'
            if mode=='plain_interrupted':
                assert not after['byte_exact'] and after['error_type']=='NameError'
            else:
                assert after['byte_exact'] and after['import_ok'] and after['value']=='complete'
            return dict(mode=mode, during=during, after_writer_exit=after,
                        original_writer_exitcode=writer.exitcode,
                        controlled_by_events_not_timed_sleep=True,
                        separate_native_processes=True)
        finally:
            release.set()
            for process in processes:
                if process.is_alive(): process.terminate()
                process.join(5)
            results.close(); results.join_thread()


def main():
    assert os.environ.get('CUDA_VISIBLE_DEVICES') == ''
    import transformers.dynamic_module_utils as dmu
    reference = Path(os.environ.get('TF_SOURCE_FILE', '/instructions/dynamic_module_utils.py'))
    # The installed native module is byte-identical to the pinned main module.
    assert Path(dmu.__file__).read_bytes() == reference.read_bytes()
    ctx = mp.get_context('spawn')
    rows = [one_case(ctx, mode) for mode in
            ['plain_concurrent', 'plain_interrupted', 'atomic_concurrent', 'atomic_interrupted']]
    print(json.dumps(dict(state='passed', cases=rows,
                         actual_cache_and_import_entrypoints=True,
                         module_sha256=hashlib.sha256(reference.read_bytes()).hexdigest(),
                         source_head='487208b35c13834746b49a1c3c6dec61b04a8ebc',
                         no_model_loaded=True, GPU=False, network=False,
                         atomic_intervention_not_upstream_patch=True,
                         no_PR_drafted_original_author_priority=True), indent=2), flush=True)


if __name__=='__main__':
    main()
mode                 reader during copy/after interruption   fresh reader after writer exit
plain_concurrent     NameError, partial bytes                complete
plain_interrupted    NameError, partial bytes                NameError, partial bytes
atomic_concurrent    complete, exact source bytes            complete
atomic_interrupted   complete, exact source bytes            complete
4/4 controlled cases passed; synchronization uses events, not timed sleeps.

This supplements the original report and proposed fix; prepared and tested with Codex assistance.

mercant1982 avatar Nov 18 '26 21:11 mercant1982

Thanks @mercant1982, that case belongs in the test. With a copy to a temporary name in the same directory and os.replace, an interrupted writer leaves only the temporary file, so the next loader copies again. I'll test an interrupted writer followed by a fresh loader next to the two-loader case.

The PR has to wait until a maintainer labels this issue triaged. Halo stages the copy this way on its side for now.

hivaze avatar Nov 19 '26 05:11 hivaze

We observed a related failure in SGLang nightly CI with Transformers 5.19.0. Our case exercises the local model directory branch of get_cached_module_file. On one worker node, 16 scheduler processes loaded the same custom tokenizer with trust_remote_code=True, sharing a cold, pod-local HF_MODULES_CACHE.

At 2026-11-13 04:35:07, five processes on that node (TP ranks 25, 17, 26, 20, and 23) failed in get_class_in_module at getattr(module, class_name). All five reported that tokenization_kimi had no attribute TikTokenTokenizer. This is consistent with a reader importing an incomplete copy. We did not capture the file contents at the instant of failure.

Could the atomic-copy fix and its regression tests also cover the local-directory branch, including files copied for relative imports?

Failed CI job · Full logs (.tar.gz)

The first traceback is on lines 568–604 of this file in the archive: main-20261113-0007-43255221761-1/Nightly_Test_NPU--main-cann9.1.0-a3/test_npu_kimi_k3_w4a8_32p_gpqa/ascend-43255221761-4ab024389w2lwujn-sglang-node-1/test_npu_kimi_k3_w4a8_32p_gpqa.log

hanwlax avatar Nov 23 '26 12:11 hanwlax

I extended the process-level repro to the local-directory branch, for both the main module and a relative import. There is a useful difference from the Hub-cache case: after an interrupted copy, a fresh local loader detects the partial destination with filecmp.cmp and repairs it. Both interrupted-writer controls passed without an atomic-copy intervention.

The concurrent publication window still exists. Two initial loaders can both decide to copy an absent file. If one copier is delayed before opening the destination, it can truncate that file after the other loader has returned from get_cached_module_file, but before that caller imports it. With event-controlled native processes, this produced NameError: UNFINISHED_CONSTANT for both the main module and the relative import. A later fresh loader repaired each file. An isolated same-directory temporary-file/os.replace copy intervention prevented both concurrent failures; it is a test control, not an upstream patch.

All eight expected outcomes were checked offline, using Transformers 5.22.2. Its entire imported dynamic_module_utils.py is byte-identical to main commit 3924952c (blob 7262c986); this does not qualify the rest of that main tree. No model, GPU or network was used during execution, and the native cache/import functions were retained.

Exact process fixture, all eight results, source binding and reproduction.

Could the local-directory regression cover this delayed second copier for both main and relative modules, alongside interrupted-writer recovery?

Prepared and tested with Codex assistance; this supplements the original author's fix.

mercant1982 avatar Nov 23 '26 18:11 mercant1982

@hanwlax @mercant1982 yes to both. The PR will stage every copy in get_cached_module_file through a temporary file in the destination directory and os.replace: the hub-cache branch, the local-directory branch and the files copied for relative imports. Its tests will cover two concurrent loaders, an interrupted writer followed by a fresh loader, and the delayed second copier, each for the main module and for a relative import.

Halo already works around it at that level. It routes every copyfile call of dynamic_module_utils through a staged copy, so the local-directory branch is covered there as well.

The PR still waits for the triaged label on this issue.

hivaze avatar Nov 27 '26 16:11 hivaze