File size: 5,207 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
"""Shared pieces of the VLMB adapters (own code, not maker code)."""
import contextlib
import os

import torch
import torch.nn.functional as F

INSTRUCTION = "Transcribe the text in this image exactly."  # amendment 3.2 C1, identical for every arm


MODE = {"precision": "pure_bf16"}


def master_dtype(precision):
    """pure_bf16 (default, as VLMA's train_vlm.py): model weights and compute in bf16, no autocast; the training
    script keeps the fp32 master copy and fp32 AdamW moments. amp_bf16: fp32 weights + bf16 autocast."""
    MODE["precision"] = precision
    return torch.float32 if precision == "amp_bf16" else torch.bfloat16


def autocast(device):
    if MODE["precision"] == "amp_bf16" and device.type in ("cuda", "cpu"):
        return torch.autocast(device_type=device.type, dtype=torch.bfloat16)
    return contextlib.nullcontext()


def target_loss_sum(logits, labels):
    """Same as VLMA vlm_common.target_loss_sum: sum of token cross-entropies over target positions (next-token
    shift), in fp32. Returns (sum, number of target tokens)."""
    lg = logits[:, :-1, :]
    lb = labels[:, 1:].to(lg.device)
    m = lb != -100
    return F.cross_entropy(lg[m].float(), lb[m], reduction="sum"), int(m.sum())


def causal_lm_loss(logits, labels):
    """Mean next-token cross-entropy over target positions (labels != -100), computed in fp32.

    logits[:, t] predicts labels[:, t+1]. Returns (loss, number of target tokens)."""
    lg = logits[:, :-1, :].float()
    lb = labels[:, 1:].to(lg.device)
    n = int((lb != -100).sum())
    loss = F.cross_entropy(lg.reshape(-1, lg.size(-1)), lb.reshape(-1), ignore_index=-100, reduction="sum")
    return loss / max(1, n), n


def assert_no_token_env():
    for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
        assert not os.environ.get(k), f"{k} is set"


def fresh_builder(cls, cfg, model_dir):
    """A function that builds the model class from a copy of its config with real (non-meta) tensors on CPU."""
    import copy

    def build():
        c = copy.deepcopy(cfg)
        c._name_or_path = model_dir  # some maker __init__ load the tokenizer from config.name_or_path
        return cls(c)
    return build


def restore_nonpersistent_buffers(model, build_fresh):
    """transformers 5 builds models on the meta device and loads only checkpoint tensors, so buffers registered with
    persistent=False (rotary frequency tables, index ranges) can be left uninitialised. This builds one fresh copy
    of the model on CPU with the maker's own __init__ (real tensors) and copies every non-persistent buffer that
    differs into the loaded model. Returns the names that were replaced."""
    fresh = build_fresh()
    fb = dict(fresh.named_buffers(remove_duplicate=False))
    fixed = []
    for mname, mod in model.named_modules(remove_duplicate=False):
        for bname in list(getattr(mod, "_non_persistent_buffers_set", ())):
            full = f"{mname}.{bname}" if mname else bname
            cur = mod._buffers.get(bname)
            ref = fb.get(full)
            if cur is None or ref is None:
                continue
            tgt = ref if (ref.is_complex() or not cur.is_floating_point()) else ref.to(cur.dtype)
            same = cur.shape == tgt.shape and cur.dtype == tgt.dtype and torch.equal(cur.detach().to("cpu"), tgt)
            if not same:
                mod._buffers[bname] = tgt.to(cur.device)
                fixed.append(full)
    del fresh
    return fixed


def remote_files_check(model_dir):
    """No compiled bytecode shipped with the repo may be importable (an unchecked-hash .pyc would run without its source)."""
    for r, ds, fs in os.walk(model_dir):
        for fn in fs:
            assert not fn.endswith((".pyc", ".pyo", ".so")), f"compiled file in model folder: {os.path.join(r, fn)}"


# ---- cap-retry rule (records/R5/RULE/r5_posttrain_experiment.txt; VLMC, 2026-11-21) -----------------------------------------
# generate(images, max_new_tokens, temperature=None): with temperature=None every adapter decodes greedily exactly as
# before and returns text; with a temperature it samples (top-k and top-p off) and, where the adapter can see the
# generated ids, returns records that say whether a stop token was emitted. The eval script seeds torch per set.
def retry_sampling(temperature):
    return {"do_sample": True, "temperature": float(temperature), "top_k": 0, "top_p": 1.0}


def stop_records(tok, new_ids, stop_ids):
    """Retry path of the HF-generate adapters: the text decoded as on the greedy path, plus whether a stop token was
    emitted among the generated ids; n_new counts the tokens before the first stop token."""
    stop = set(stop_ids) if isinstance(stop_ids, (list, tuple, set)) else {stop_ids}
    texts = tok.batch_decode(new_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
    recs = []
    for row, t in zip(new_ids.tolist(), texts):
        k = next((i for i, x in enumerate(row) if x in stop), None)
        recs.append({"raw": t, "n_new": k if k is not None else len(row), "hit_cap": k is None, "eos": k is not None,
                     "conf": None, "conf_min": None, "stop_source": "adapter: generated ids"})
    return recs