Spaces:
Running on Zero
Running on Zero
Stage fixed-case Gradio ZeroGPU demo
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+6
- README.md+10-6
- app.pyAdded+126
- caption/beam.pyAdded+42
- caption/cama_reference.pyAdded+46
- caption/model.pyAdded+36
- caption/runner.pyAdded+87
- caption/visual.pyAdded+47
- data/levir/config.jsonAdded+1
- data/levir/vocab.jsonAdded+1
- inference.pyAdded+98
- judge/event_reward_v7.pyAdded+369
- judge/legacy_event_parse.pyAdded+84
- judge/qa_reward.pyAdded+465
- judge/qa_reward_v2.pyAdded+116
- judge/questions.pyAdded+83
- judge/runner.pyAdded+52
- judge/stage1_runtime.pyAdded+150
- judge/stage2_runtime.pyAdded+158
- pipeline.pyAdded+142
- public/cases.jsonAdded+1
- public/images/test_000033_A.pngAdded
- public/images/test_000033_B.pngAdded
- public/images/test_001095_A.pngAdded
- public/images/test_001095_B.pngAdded
- public/images/test_001324_A.pngAdded
- public/images/test_001324_B.pngAdded
- public/images/test_001549_A.pngAdded
- public/images/test_001549_B.pngAdded
- requirements.txtAdded+19
- vendor/NOTICE.mdAdded+5
- vendor/OneJev/LICENSEAdded+202
- vendor/OneJev/modeling_qwen3_5.py.referenceAdded+1971
- vendor/OneJev/qev/__init__.pyAdded+4
- vendor/OneJev/qev/answers.pyAdded+74
- vendor/OneJev/qev/calibrate.pyAdded+114
- vendor/OneJev/qev/client.pyAdded+114
- vendor/OneJev/qev/prompt.pyAdded+168
- vendor/OneJev/qev/readout.pyAdded+269
- vendor/OneJev/qev/schema.pyAdded+118
- vendor/OneJev/train/__init__.pyAdded+1
- vendor/OneJev/train/common.pyAdded+676
- vendor/OneJev/train/mm.pyAdded+172
- vendor/metrics/LICENSEAdded+26
- vendor/metrics/__init__.pyAdded
- vendor/metrics/bleu/LICENSEAdded+19
- vendor/metrics/bleu/__init__.pyAdded+1
- vendor/metrics/bleu/bleu.pyAdded+44
- vendor/metrics/bleu/bleu_scorer.pyAdded+263
- vendor/metrics/cider/__init__.pyAdded+1
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373839404132 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textpublic/images/test_000033_A.png filter=lfs diff=lfs merge=lfs -textpublic/images/test_000033_B.png filter=lfs diff=lfs merge=lfs -textpublic/images/test_001095_A.png filter=lfs diff=lfs merge=lfs -textpublic/images/test_001324_A.png filter=lfs diff=lfs merge=lfs -textpublic/images/test_001549_A.png filter=lfs diff=lfs merge=lfs -textpublic/images/test_001549_B.png filter=lfs diff=lfs merge=lfs -text
12345678910111213---title: Critique Then Rerank ZeroGPUemoji: 🦀colorFrom: indigocolorTo: pinksdk: gradiosdk_version: 6.33.0python_version: '3.12'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314151617---title: Critique-then-Rerank · Live Inferenceemoji: 🛰️colorFrom: greencolorTo: graysdk: gradiosdk_version: 6.33.0python_version: 3.12.12app_file: app.pypinned: false---# Critique-then-Rerank · Live InferenceSelect one of four LEVIR-CC image pairs and run Beam-15 generation and two-stage state-locked reranking. The app does not accept uploads or serve archived predictions as live output. [Project page](https://thirteen7.github.io/Critique-then-Rerank/)For deployment, select ZeroGPU hardware in Space Settings. Set `CTR_MODEL_READ_TOKEN` as a **Space secret** using a fine-grained token with read access only to `thirteen7/Critique-then-Rerank`. Do not use an account-wide token. The pinned public RSCaMa and Elephant-1 checkpoints are downloaded directly from the Hub; they are not bundled. The first startup after configuration downloads the checkpoints before accepting GPU work.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126"""Fixed-case Gradio interface for the LEVIR-CC live demo."""
from html import escapeimport loggingimport os
import spacesimport gradio as grfrom PIL import Image
from inference import prepare, run_casefrom pipeline import ROOT, read
LOGGER = logging.getLogger(__name__)PUBLIC = ROOT / 'public'CASES = {record['name']: record for record in read(PUBLIC / 'cases.json')}FIRST = next(iter(CASES))HERO = '''<header class="observatory"> <div class="eyebrow">REMOTE SENSING / LEVIR-CC <span>ZERO GPU</span></div> <h1>Critique-then-Rerank</h1> <p>One image pair, 15 captions, two decisions. See how the model first decides whether anything changed, then refines the caption without changing that decision.</p> <p>选择一组双时相影像,观察模型如何锁定变化状态,再在同状态候选中精排。</p> <a href="https://thirteen7.github.io/Critique-then-Rerank/">Project page / 项目主页 ↗</a></header>'''CSS = '''.gradio-container { max-width: 1100px !important; }.observatory { padding: clamp(1.25rem, 5vw, 3.5rem); border-radius: 1.25rem; color: #f0f8f4; background: radial-gradient(ellipse at 100% 0%, #245b51, #122520 65%); }.observatory h1 { color: inherit; font-size: clamp(2rem, 6vw, 4rem); line-height: 1.04; margin: 1rem 0; }.observatory p { color: #dbebe5; max-width: 58ch; margin: .65rem 0; }.observatory a { color: #b6f6dd; text-decoration: underline; }.eyebrow { font-family: monospace; letter-spacing: .14em; color: #b6f6dd; }.eyebrow span { display: inline-block; margin-inline-start: .75rem; color: #fff7ed; }#run-live { min-height: 3rem; }.decision-card { border: 1px solid var(--border-color-primary); border-radius: .75rem; padding: 1rem; }.decision-card h3 { margin: 0 0 .5rem; }.decision-card p { overflow-wrap: anywhere; }.decision-card.final { border-width: 2px; border-color: #0f766e; }.decision-card.routed { border-color: #d95d39; }'''
def previews(case_name): return tuple(load_preview(PUBLIC / image) for image in CASES[case_name]['media'])
def load_preview(path): with Image.open(path) as image: return image.convert('RGB')
def cards(result): captions = result['captions'] state = 'Changed / 有变化' if result['changed'] else 'Unchanged / 无变化' if not result['changed']: route = 'Bypassed / 跳过精排' elif len(result['stage2']) > 1: route = f"Reranked {len(result['stage2'])} same-state candidates / 同状态精排 · β = {result['beta']:.2f}" elif result['stage2']: route = 'One eligible candidate / 仅一条合格候选' else: route = 'No eligible candidates; retained Stage 1 / 无合格候选,保留第一阶段结果' return ( f"### {result['name']} · Live result / 实时结果", f'<div class="decision-card"><h3>01 · Beam-15 Top-1</h3><p lang="en">{escape(captions[0])}</p></div>', f'<div class="decision-card"><h3>02 · State Gate</h3><p>{state}</p>' f'<p lang="en">{escape(captions[result["anchor"]])}</p></div>', f'<div class="decision-card final {"routed" if result["changed"] else ""}">' f'<h3>03 · Final Caption</h3><p>{route}</p><p lang="en">{escape(captions[result["final"]])}</p></div>', [[index + 1, caption] for index, caption in enumerate(captions)], )
def load_checkpoints(): token = os.environ.get('CTR_MODEL_READ_TOKEN') if not token: return None try: return prepare(token) except Exception as error: LOGGER.error('Checkpoint preparation failed (%s). Check Space secret permissions and model availability.', type(error).__name__) return None
@spaces.GPU(duration=120)def run_live(case_name): if case_name not in CASES: raise gr.Error('Select a listed image pair. / 请选择列出的影像组。') if CHECKPOINTS is None: raise gr.Error('Model weights are not configured. / 尚未配置模型权重。') return cards(run_case(CASES[case_name], CHECKPOINTS))
def build(): with gr.Blocks(title='Critique-then-Rerank · Live', analytics_enabled=False) as app: gr.HTML(HERO) if CHECKPOINTS is None: gr.Markdown('**Live inference unavailable / 实时推理暂不可用。** ' 'This Space cannot access the model weights. / 当前 Space 未能读取模型权重。') case = gr.Radio([(f"{record['en']} / {record['zh']} · {name}", name) for name, record in CASES.items()], value=FIRST, label='Test pair / 选择样例') before_img, after_img = previews(FIRST) with gr.Row(): before = gr.Image(before_img, label='T₁ · Before / 变化前', interactive=False, buttons=[], height=300) after = gr.Image(after_img, label='T₂ · After / 变化后', interactive=False, buttons=[], height=300) run = gr.Button('Run live inference / 运行实时推理', variant='primary', elem_id='run-live', interactive=CHECKPOINTS is not None) heading = gr.Markdown('### Decision trace / 决策过程') with gr.Row(): top, gate, final = gr.HTML(), gr.HTML(), gr.HTML() with gr.Accordion('Beam-15 candidates / 15 条候选', open=False): candidates = gr.Dataframe(headers=['Beam rank', 'Caption'], datatype=['number', 'str'], interactive=False) case.change(previews, case, [before, after], queue=False, api_visibility='private') run.click(run_live, case, [heading, top, gate, final, candidates], concurrency_limit=1, api_name='run_case', api_visibility='undocumented') return app.queue(max_size=8)
if __name__ == '__main__': CHECKPOINTS = load_checkpoints() build().launch(css=CSS, theme=gr.themes.Soft(primary_hue='teal', neutral_hue='slate'), show_error=False)123456789101112131415161718192021222324252627282930313233343536373839404142"""The LEVIR control's cumulative-log-probability native beam decoder."""import torch
MAX_TOKENS = 42
def beam_sequences(model, features, width, length_penalty=0.0): batch = len(features) device = features.device prefixes = torch.zeros((batch, width, 1), device=device, dtype=torch.long) scores = torch.full((batch, width), -torch.inf, device=device) scores[:, 0] = 0 ended = torch.zeros_like(scores, dtype=torch.bool) lengths = torch.zeros_like(scores, dtype=torch.long) repeated = features.repeat_interleave(width, 0) parent_batch = torch.arange(batch, device=device)[:, None] for _ in range(MAX_TOKENS): next_logp = model.logits(repeated, prefixes.flatten(0, 1))[:, -1].log_softmax(-1) next_logp = next_logp.reshape(batch, width, -1) next_logp = next_logp.masked_fill(ended[..., None], -torch.inf) next_logp[..., 0] = torch.where(ended, 0.0, next_logp[..., 0]) vocabulary_size = next_logp.shape[-1] cumulative = scores[..., None] + next_logp candidate_lengths = lengths + (~ended).long() ranked = cumulative if length_penalty: ranked = cumulative / candidate_lengths.clamp_min(1)[..., None].pow(length_penalty) _, expansion = ranked.flatten(1).topk(width, dim=1) scores = cumulative.flatten(1).gather(1, expansion) parent = expansion.div(vocabulary_size, rounding_mode="floor") word = expansion % vocabulary_size prefixes = torch.cat((prefixes[parent_batch, parent], word[..., None]), dim=-1) lengths = candidate_lengths[parent_batch, parent] ended = ended[parent_batch, parent] | word.eq(0) if bool(ended.all()): break assert torch.isfinite(scores).all() beams = [ [sequence[:sequence.index(0)] if 0 in sequence else sequence for sequence in paths] for paths in prefixes[:, :, 1:].tolist() ] return beams, scores.tolist()12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""PyTorch reference kernels for frozen CaMa feature extraction."""
import torchfrom torch.nn import functional as F
def causal_convolution(sequence, weight, bias=None, activation=None): width = sequence.shape[-1] result = F.conv1d(sequence, weight.unsqueeze(1), bias, padding=weight.shape[-1] - 1, groups=sequence.shape[1])[..., :width] if activation not in (None, 'silu', 'swish'): raise ValueError(f'Unsupported CaMa activation: {activation}') return F.silu(result) if activation is not None else result
def selective_scan(inputs, delta, decay, in_scale, out_scale, skip=None, gate=None, bias=None, delta_softplus=False, return_last_state=False): dtype = inputs.dtype inputs, delta = inputs.float(), delta.float() if bias is not None: delta = delta + bias.float()[:, None] if delta_softplus: delta = F.softplus(delta) transition = torch.exp(torch.einsum('bdl,dn->bdln', delta, decay)) drive = torch.einsum('bdl,bnl,bdl->bdln', delta, in_scale.float(), inputs) state = torch.zeros_like(transition[:, :, 0]) values = [] for position in range(inputs.shape[-1]): state = transition[:, :, position] * state + drive[:, :, position] values.append(torch.einsum('bdn,bn->bd', state, out_scale[:, :, position].float())) output = torch.stack(values, dim=-1) if skip is not None: output = output + inputs * skip[:, None] if gate is not None: output = output * F.silu(gate) output = output.to(dtype) return (output, state) if return_last_state else output
def install(): from vendor.rscama import mamba_block
if not mamba_block.is_fast_path_available: mamba_block.causal_conv1d_fn = causal_convolution mamba_block.selective_scan_fn = selective_scan mamba_block.is_fast_path_available = True123456789101112131415161718192021222324252627282930313233343536"""Caption decoder used for Beam-15 inference."""import torchfrom torch import nn
from vendor.rscama.model_decoder import DecoderTransformer
class ChangeCaptioner(nn.Module): def __init__(self, vocab): super().__init__() self.decoder = DecoderTransformer('transformer_decoder', 768, len(vocab), 42, vocab, 8, 1, .1) # The training vocabulary uses 0 for BOS/EOS/PAD; the official vocabulary # has separate special IDs. This mapping preserves the original logits. self.register_buffer('output_ids', torch.tensor([3, 1] + list(range(4, len(vocab)))), persistent=False)
def logits(self, features, prefix): old = torch.where(prefix >= 2, prefix + 2, prefix).clone() old[:, 0] = 2 length = prefix.shape[1] causal = torch.triu(torch.full((length, length), float('-inf'), device=prefix.device), 1) d = self.decoder x = d.position_encoding(d.vocab_embedding(old.T)) x = d.transformer(x, features.permute(2, 0, 1), tgt_mask=causal, tgt_key_padding_mask=old.eq(0)) return d.wdc(d.dropout(x)).transpose(0, 1).index_select(-1, self.output_ids)
def load_captioner(vocab, weights, device): model = ChangeCaptioner(vocab) state = torch.load(weights, map_location='cpu', weights_only=True, mmap=True) if 'model' in state: model.load_state_dict(state['model']) elif 'decoder_dict' in state: model.decoder.load_state_dict(state['decoder_dict']) else: model.decoder.load_state_dict(state) return model.to(device)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687"""Frozen feature extraction and Beam-15 decoding."""
import random
import numpy as npfrom PIL import Imageimport torch
from pipeline import ROOT, readfrom .beam import beam_sequencesfrom .model import load_captionerfrom .visual import FrozenVisualModel
def initialize(): random.seed(17) np.random.seed(17) torch.manual_seed(17) torch.set_num_threads(8) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False torch.backends.cudnn.benchmark = False
def get_vocab(dataset): return read(ROOT / 'data' / dataset / 'vocab.json')
def native_captioner(dataset, weights, device): vocab = get_vocab(dataset) native_to_word = {1 if value == 1 else value - 2: word for word, value in vocab.items() if value == 1 or value >= 4} return load_captioner(vocab, weights, device), native_to_word
def image_features(dataset, split, records, image_root, weights, device): extractor = FrozenVisualModel(weights, device) batch_size = 1 if dataset == 'levir' and split != 'train' else 16 chunks = [] for offset in range(0, len(records), batch_size): pairs = [] for record in records[offset:offset + batch_size]: tensors = [] for name in record['media']: with Image.open(image_root / name) as image: image = image.convert('RGB') if dataset == 'dubai': image = image.resize((256, 256), Image.Resampling.BILINEAR) tensors.append(extractor.preprocess(image)) pairs.append(tensors) before, after = (torch.stack(period).to(device) for period in zip(*pairs, strict=True)) features = extractor(before, after) if not features.isfinite().all(): raise RuntimeError(f'{dataset}/{split}: non-finite visual features at offset {offset}') chunks.append(features.cpu()) return torch.cat(chunks)
def features_for(dataset, split, records, args): names = [row['name'] for row in records] if args.features is not None: value = torch.load(args.features / f'{split}.pt', map_location='cpu', mmap=True, weights_only=True) if value['names'][:len(names)] != names or value['features'].shape[1:] != (768, 49): raise ValueError(f'{dataset}/{split}: feature cache names or dimensions do not match') return value['features'][:len(names)] if args.images is None or args.visual is None: raise ValueError('Pass --features, or both --images and --visual.') return image_features(dataset, split, records, args.images, args.visual, args.device)
def decode(words, sequence): output = [] for token in sequence: if token == 0: break output.append(words[token]) return ' '.join(output)
@torch.no_grad()def beam(dataset, features, weights, device): model, words = native_captioner(dataset, weights, device) model.eval() captions = [] for group in features.split(16): beams, _ = beam_sequences(model, group.to(device), width=15) captions.extend([[decode(words, path) for path in image] for image in beams]) return captions1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Frozen CLIP spatial encoding and RSCaMa temporal fusion."""import torchfrom torch import nn
class VisualEncoder(nn.Module): def __init__(self, state): super().__init__() from clip.model import VisionTransformer self.visual = VisionTransformer(input_resolution=224, patch_size=32, width=768, layers=12, heads=12, output_dim=512) prefix = 'clip_model.visual.' self.visual.load_state_dict({k[len(prefix):]: value for k, value in state.items() if k.startswith(prefix)})
def forward(self, image): v = self.visual x = v.conv1(image) x = x.reshape(x.shape[0], x.shape[1], -1).permute(0, 2, 1) cls = v.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device) x = torch.cat([cls, x], dim=1) x = v.ln_pre(x + v.positional_embedding.to(x.dtype)) x = v.transformer(x.permute(1, 0, 2)).permute(1, 0, 2) return x[:, 1:, :]
class FrozenVisualModel(nn.Module): def __init__(self, weights, device='cuda'): super().__init__() from clip.clip import _transform from .cama_reference import install from vendor.rscama.model_encoder_attMamba import AttentiveEncoder
if torch.device(device).type != 'cuda': raise ValueError('CaMa image feature extraction requires a CUDA device.') install() state = torch.load(weights, map_location='cpu', weights_only=True, mmap=True) self.encoder = VisualEncoder(state['encoder_dict']) self.change_fusion = AttentiveEncoder(n_layers=3, feature_size=[7, 7, 768], heads=8, dropout=.1) result = self.change_fusion.load_state_dict(state['encoder_trans_dict'], strict=False) if result.unexpected_keys or any(not key.endswith('.embeddings.weight') for key in result.missing_keys): raise ValueError(f'Incompatible visual checkpoint: {result}') self.preprocess = _transform(224) self.to(device).eval().requires_grad_(False)
@torch.no_grad() def forward(self, before, after): return self.change_fusion(self.encoder(before), self.encoder(after))1{"templates":["there is no difference","the two scenes seem identical","the scene is the same as before","no change has occurred","almost nothing has changed"],"beta":0.12,"paper_metrics":{"BLEU1":89.25,"BLEU2":82.13,"BLEU3":75.29,"BLEU4":69.35,"METEOR":41.92,"ROUGE_L":77.41,"CIDEr":147.65,"S_m_star":84.08},"paper_prediction_sha256":"8837eb0765c0ba43ebf275c728e8007e4d90ac451ab3e02d89b0f821093d4d4e","paper_endpoints":{"generator_epoch":9,"stage1_step":500,"stage2_step":1278},"generator":{"epochs":10,"batch":10,"samples":5,"rate":5e-05,"floor":1e-06,"hold_epochs":3},"stage1":{"total_updates":2000,"learning_rate_peak":2e-05,"learning_rate_final":2e-06,"warmup_steps":100,"gradient_clip_norm":1.0,"eval_steps":[250,500,750,1000,1250,1500,1750,2000],"brier":1.0},"stage2":{"total_updates":2556,"epochs":3,"steps_per_epoch":852,"global_batch":8,"learning_rate_peak":1e-05,"learning_rate_final":1e-06,"warmup_steps":86,"gradient_clip_norm":1.0,"rank":8,"alpha":16,"optimizer_betas":[0.9,0.95],"rank_batch":4,"projection_learning_rate_peak":5e-06,"projection_learning_rate_final":5e-07,"eval_steps":[0,426,852,1278,1704,2130,2556]}}1{"<NULL>": 0, "<UNK>": 1, "<START>": 2, "<END>": 3, "a": 4, "abandoned": 5, "above": 6, "across": 7, "added": 8, "additional": 9, "all": 10, "almost": 11, "along": 12, "alongside": 13, "among": 14, "an": 15, "and": 16, "angle": 17, "another": 18, "appear": 19, "appeared": 20, "appears": 21, "arc": 22, "are": 23, "area": 24, "areas": 25, "around": 26, "arranged": 27, "as": 28, "asphalt": 29, "at": 30, "attached": 31, "bank": 32, "bare": 33, "bareland": 34, "barelands": 35, "basketball": 36, "become": 37, "becomes": 38, "been": 39, "before": 40, "behind": 41, "below": 42, "beside": 43, "besides": 44, "between": 45, "big": 46, "bigger": 47, "block": 48, "blocks": 49, "blue": 50, "both": 51, "bottom": 52, "boxes": 53, "branch": 54, "branches": 55, "bridges": 56, "broadened": 57, "brushwoods": 58, "build": 59, "building": 60, "buildings": 61, "built": 62, "bungalow": 63, "bungalows": 64, "bushes": 65, "but": 66, "by": 67, "bypass": 68, "bypasses": 69, "car": 70, "cars": 71, "cement": 72, "center": 73, "central": 74, "certain": 75, "change": 76, "changed": 77, "circle": 78, "circular": 79, "cleared": 80, "clearing": 81, "closely": 82, "cluster": 83, "comes": 84, "completed": 85, "complex": 86, "complexes": 87, "concrete": 88, "connected": 89, "connecting": 90, "connects": 91, "consisting": 92, "constructed": 93, "construction": 94, "constructions": 95, "containers": 96, "continues": 97, "converge": 98, "converted": 99, "corner": 100, "corners": 101, "cottage": 102, "court": 103, "courts": 104, "covered": 105, "cross": 106, "crossing": 107, "crossroad": 108, "crossroads": 109, "curve": 110, "curved": 111, "cut": 112, "decreased": 113, "decreases": 114, "demolished": 115, "dense": 116, "densely": 117, "denser": 118, "depots": 119, "desert": 120, "detached": 121, "developed": 122, "difference": 123, "different": 124, "directions": 125, "dirt": 126, "disappear": 127, "disappeared": 128, "disappears": 129, "distributed": 130, "divide": 131, "divided": 132, "down": 133, "dry": 134, "each": 135, "edge": 136, "either": 137, "empty": 138, "end": 139, "enlarged": 140, "erected": 141, "existing": 142, "expanded": 143, "extend": 144, "extended": 145, "extends": 146, "extra": 147, "face": 148, "facilities": 149, "factory": 150, "fades": 151, "few": 152, "fewer": 153, "field": 154, "fields": 155, "fill": 156, "filled": 157, "finished": 158, "five": 159, "flat": 160, "flattened": 161, "floor": 162, "for": 163, "forest": 164, "forests": 165, "form": 166, "formed": 167, "former": 168, "foundation": 169, "four": 170, "from": 171, "front": 172, "full": 173, "giant": 174, "going": 175, "grass": 176, "grassland": 177, "greatly": 178, "green": 179, "greener": 180, "ground": 181, "group": 182, "groups": 183, "grow": 184, "growing": 185, "grown": 186, "grows": 187, "half": 188, "has": 189, "have": 190, "higher": 191, "hole": 192, "horizontal": 193, "house": 194, "houses": 195, "huge": 196, "identical": 197, "image": 198, "in": 199, "increased": 200, "increases": 201, "intersect": 202, "intersecting": 203, "intersection": 204, "into": 205, "is": 206, "it": 207, "its": 208, "join": 209, "joint": 210, "jungle": 211, "lake": 212, "land": 213, "lane": 214, "large": 215, "larger": 216, "leading": 217, "left": 218, "less": 219, "level": 220, "leveled": 221, "line": 222, "lined": 223, "lines": 224, "located": 225, "long": 226, "longer": 227, "lot": 228, "lots": 229, "lower": 230, "lower-left": 231, "lower-right": 232, "lush": 233, "lusher": 234, "luxuriant": 235, "main": 236, "make": 237, "mall": 238, "malls": 239, "mansion": 240, "mansions": 241, "many": 242, "massive": 243, "meadow": 244, "meadows": 245, "medium": 246, "middle": 247, "missing": 248, "moorland": 249, "more": 250, "most": 251, "mounds": 252, "moved": 253, "much": 254, "narrow": 255, "near": 256, "nearby": 257, "neat": 258, "neatly": 259, "new": 260, "newly": 261, "next": 262, "no": 263, "nothing": 264, "number": 265, "occurred": 266, "of": 267, "old": 268, "on": 269, "one": 270, "ones": 271, "only": 272, "open": 273, "opposite": 274, "orderly": 275, "original": 276, "other": 277, "others": 278, "out": 279, "overpasses": 280, "parallel": 281, "park": 282, "parked": 283, "parking": 284, "part": 285, "parts": 286, "pasture": 287, "path": 288, "paths": 289, "picture": 290, "piece": 291, "place": 292, "places": 293, "planted": 294, "plants": 295, "platform": 296, "playground": 297, "playgrounds": 298, "playing": 299, "pond": 300, "ponds": 301, "pool": 302, "pools": 303, "pulled": 304, "quantity": 305, "raw": 306, "realized": 307, "rebuilt": 308, "reconstructed": 309, "rectangular": 310, "red": 311, "reduced": 312, "remaining": 313, "removed": 314, "renovated": 315, "replace": 316, "replaced": 317, "replaces": 318, "replacing": 319, "reservoir": 320, "reshaped": 321, "residential": 322, "respective": 323, "restored": 324, "right": 325, "ring": 326, "risen": 327, "river": 328, "road": 329, "roads": 330, "roadside": 331, "roadsides": 332, "roof": 333, "room": 334, "rooms": 335, "round": 336, "roundabout": 337, "row": 338, "rows": 339, "rugged": 340, "run": 341, "running": 342, "runs": 343, "same": 344, "scattered": 345, "scene": 346, "scenes": 347, "screen": 348, "seem": 349, "separate": 350, "several": 351, "shaped": 352, "show": 353, "shows": 354, "shrubs": 355, "side": 356, "sides": 357, "similar": 358, "single": 359, "site": 360, "sites": 361, "situated": 362, "six": 363, "small": 364, "smaller": 365, "some": 366, "space": 367, "spaced": 368, "spaces": 369, "sparse": 370, "square": 371, "squares": 372, "stadium": 373, "staggered": 374, "stand": 375, "storage": 376, "straight": 377, "street": 378, "streets": 379, "stretch": 380, "stretches": 381, "structure": 382, "structures": 383, "stuff": 384, "sundries": 385, "surround": 386, "surrounded": 387, "surrounding": 388, "surrounds": 389, "swimming": 390, "t": 391, "t-junction": 392, "t-shaped": 393, "take": 394, "takes": 395, "tank": 396, "tanks": 397, "that": 398, "the": 399, "them": 400, "there": 401, "thicker": 402, "this": 403, "three": 404, "through": 405, "to": 406, "top": 407, "tower": 408, "track": 409, "tracks": 410, "trail": 411, "trails": 412, "transformed": 413, "tree": 414, "trees": 415, "trucks": 416, "turn": 417, "turned": 418, "turning": 419, "turns": 420, "two": 421, "u-shaped": 422, "uncompleted": 423, "under": 424, "uneven": 425, "unsurfaced": 426, "up": 427, "upper": 428, "vacant": 429, "vanished": 430, "vanishes": 431, "vegetation": 432, "vehicles": 433, "vertical": 434, "viaduct": 435, "viaducts": 436, "vibrant": 437, "villa": 438, "village": 439, "villas": 440, "vitals": 441, "warehouse": 442, "warehouses": 443, "was": 444, "wasteland": 445, "water": 446, "well": 447, "were": 448, "where": 449, "which": 450, "while": 451, "white": 452, "wide": 453, "widened": 454, "widens": 455, "wider": 456, "width": 457, "winding": 458, "with": 459, "withered": 460, "wood": 461, "woodland": 462, "woodlands": 463, "woods": 464, "yard": 465, "yards": 466, "yellow": 467}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Run the recorded LEVIR inference pipeline in a single ZeroGPU lease."""
from dataclasses import dataclassimport gcfrom importlib import metadata, utilfrom importlib.machinery import SourceFileLoaderfrom pathlib import Pathimport sys
from huggingface_hub import hf_hub_download, snapshot_download
from pipeline import ROOT, decision, next_stage, profile
MODEL_REPO = 'thirteen7/Critique-then-Rerank'MODEL_REVISION = 'e0332dbdd6727dfd800480ca8a7cddf1912b0c52'BASE_REPO = 'baselabs/elephant-1'BASE_REVISION = 'b3f8a93462fb1051a9de031e94a7ff380e254072'VISUAL_REPO = 'lcybuaa/RSCaMa'VISUAL_REVISION = '3e527e6656b62cc615eab1d2f3fb73777cbbf62c'
@dataclass(frozen=True)class Checkpoints: visual: Path generator: Path base: Path adapters: Path
def prepare(token): weights = Path(snapshot_download( MODEL_REPO, revision=MODEL_REVISION, token=token, allow_patterns=[ 'weights/levir/generator.pt', 'weights/levir/stage[12]/adapter_config.json', 'weights/levir/stage[12]/adapter_model.safetensors', ], )) / 'weights/levir' base = Path(snapshot_download(BASE_REPO, revision=BASE_REVISION, token=False)) visual = Path(hf_hub_download(VISUAL_REPO, 'RSCaMa.pth', revision=VISUAL_REVISION, token=False)) return Checkpoints(visual, weights / 'generator.pt', base, weights)
def install_elephant_model(): if metadata.version('transformers') != '5.19.0': raise RuntimeError('This demo requires the pinned Transformers release.') module_name = 'transformers.models.qwen3_5.modeling_qwen3_5' source = ROOT / 'vendor/OneJev/modeling_qwen3_5.py.reference' if module_name in sys.modules: if Path(sys.modules[module_name].__file__) != source: raise RuntimeError('Unpatched Qwen3.5 was imported before the Elephant runtime.') return loader = SourceFileLoader(module_name, str(source)) spec = util.spec_from_loader(module_name, loader) module = util.module_from_spec(spec) sys.modules[module_name] = module try: loader.exec_module(module) except Exception: del sys.modules[module_name] raise
def run_case(record, checkpoints): import torch from caption.runner import beam, image_features, initialize from judge.questions import stage1_questions, stage2_questions from judge.runner import load, score
if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): raise RuntimeError('A BF16-capable CUDA GPU is required.') install_elephant_model() initialize() dataset = 'levir' media_root = ROOT / 'public' config = profile(dataset) name = record['name'] features = image_features(dataset, 'test', [record], media_root, checkpoints.visual, 'cuda') captions = beam(dataset, features, checkpoints.generator, 'cuda')[0] row = {'name': name, 'captions': captions} rows = {name: row}
for stage in (1, 2): questions = list(stage1_questions(dataset, [record], rows) if stage == 1 else stage2_questions(dataset, [record], rows, config['templates'])) if not questions: continue runtime, bundle = load(dataset, stage, checkpoints.base, media_root, checkpoints.adapters / f'stage{stage}') try: row[f'stage{stage}'] = score(runtime, bundle, questions)[name] finally: del bundle gc.collect() torch.cuda.empty_cache()
anchor = max(row['stage1'], key=lambda pair: pair[1])[0] _, changed = next_stage(dataset, captions, anchor, config['templates']) return {**row, 'anchor': anchor, 'changed': changed, 'beta': config['beta'], 'final': decision(dataset, row, config['beta'], config['templates'])}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369"""Caption-only event binding with confirmed, absent and unknown fact states."""from __future__ import annotations
from collections import Counterfrom copy import deepcopyimport re
from . import qa_reward as legacyfrom . import qa_reward_v2 as syntax
OBJECT_PATTERNS = { "building": r"buildings?|houses?|villas?|bungalows?|factories|factory|warehouses?", "road": r"roads?|streets?|highways?|crossroads?", "vegetation": r"vegetation|trees?|plants?|forests?|woods?|grass(?:land)?|shrub(?:s|land)?", "water": r"lakes?|ponds?|pools?|rivers?|water", "bareland": r"bareland|bare land|open space", "farmland": r"farmland|farm land|cropland|fields?", "parking": r"parking lots?|parking areas?",}ENTITY = re.compile(r"\b(?:" + "|".join(OBJECT_PATTERNS.values()) + r")\b")OBJECTS = {key: re.compile(r"^(?:" + pattern + r")$") for key, pattern in OBJECT_PATTERNS.items()}ADD = re.compile(r"^(?:" + legacy._legacy.ADD + r"|erected|planted)$")REMOVE = re.compile(r"^(?:" + legacy._legacy.REMOVE + r"|cleared|cut down|cut|deforested)$")VERB = re.compile( r"\b(?:" + legacy._legacy.ADD + "|" + legacy._legacy.REMOVE + "|" + legacy._legacy.MODIFY + r"|replaced by|replaces?|replaced|turned into|turns? into|erected|planted|cleared|cut down|deforested)\b")LANDMARK = re.compile( r"\b(?P<relation>near|beside|around|along|alongside|next to|adjacent to|" r"on (?:both|either) sides? of)\s+(?:(?:a|an|the|some|many|new|old)\s+)*" r"(?P<object>" + "|".join(OBJECT_PATTERNS.values()) + r")\b")
def object_name(text): return next((key for key, pattern in OBJECTS.items() if pattern.fullmatch(text)), None)
def split_clauses(text): result = [] for clause in re.split(r"[.;]|\b(?:while|but)\b", text): verbs = list(VERB.finditer(clause)) boundaries = [] for first, second in zip(verbs, verbs[1:]): gap = clause[first.end():second.start()] for join in reversed(list(re.finditer(r"\band\b|,", gap))): if ENTITY.search(gap[join.end():]): boundaries.append(first.end() + join.start()) break start = 0 for end in boundaries: result.append(clause[start:end].strip(" ,")) separator = re.match(r"(?:and\b|,)\s*", clause[end:]) start = end + len(separator.group()) result.append(clause[start:].strip(" ,")) return [re.sub(r"^and\s+", "", value) for value in result if value]
def subject_objects(prefix): core = legacy._subject_core(prefix) # "a road with houses built along it" binds the reduced predicate to houses. contexts = list(re.finditer(r"\bwith\b", prefix)) if contexts: tail = prefix[contexts[-1].end():] if ENTITY.search(tail) and not re.search(r"\b(?:is|are|was|were|has|have|been|being)\b", tail): core = legacy._subject_core(tail) mentions = list(ENTITY.finditer(core)) for left, right in zip(mentions, mentions[1:]): if object_name(left.group()) != object_name(right.group()) and not re.search( r"\band\b|,", core[left.end():right.start()] ): return [], core return sorted({object_name(match.group()) for match in mentions}), core
def event_location(prefix, suffix): region, status = legacy._event_location(prefix, suffix) landmarks = list(LANDMARK.finditer(prefix + " " + suffix)) relation = None if len(landmarks) == 1: relation = "near:" + object_name(landmarks[0]["object"]) return region, status, relation
def parse_clause(clause): # A trailing unknown token does not erase an already completed predicate. cleaned = re.sub(r"(?:\s+<unk>)+$", "", clause) if re.search(r"<[^>]*>|[?]", cleaned) or legacy._UNCERTAIN.search(cleaned): return [], "uncertain_or_malformed_clause" cleaned = syntax._canonical_clause(cleaned) verbs = list(VERB.finditer(cleaned)) if len(verbs) != 1: return [], "unrecognized_predicate" verb = verbs[0] prefix, suffix = cleaned[:verb.start()], cleaned[verb.end():] subjects, _ = subject_objects(prefix) action = verb.group() transition = action in { "replaced by", "turned into", "turn into", "turns into", "replace", "replaces", "replaced", } if transition: results, _ = subject_objects(suffix) if not subjects or not results: return [], "unresolved_transition" passive = action == "replaced by" or "into" in action sides = [ (subjects, "removed" if passive else "added"), (results, "added" if passive else "removed"), ] else: if not subjects and re.search(r"\b(?:new|newly)\s*$", prefix): subjects, _ = subject_objects(suffix) prefix = "" if not subjects: return [], "unrecognized_event_subject" direction = "added" if ADD.fullmatch(action) else "removed" if REMOVE.fullmatch(action) else "other" sides = [(subjects, direction)] region, status, relation = event_location(prefix, suffix) return [ { "object": subject, "action": direction, "location": region, "location_status": status, "relation": relation, "evidence": clause, } for subjects, direction in sides for subject in subjects ], None
def extract_caption(caption): if not isinstance(caption, str) or not caption.strip(): return legacy.extract_caption(caption) text = legacy._normalize(caption) if text in legacy.NC_TEMPLATES or "?" in text: return legacy.extract_caption(caption) events, unchanged, generic, unresolved = [], [], [], [] for clause in split_clauses(text): if clause in legacy.NC_TEMPLATES or ( legacy._legacy.GLOBAL_NO.search(clause) and not ENTITY.search(clause) ): unchanged.append(clause) continue if legacy._GENERIC_CHANGE.fullmatch(clause): generic.append(clause) continue parsed, reason = parse_clause(clause) events.extend(parsed) if reason: unresolved.append({"text": clause, "reason": reason}) changed = [event["evidence"] for event in events] + generic if changed and unchanged: state, evidence = None, [] unresolved.append({"text": text, "reason": "conflicting_change_state"}) elif changed: state, evidence = "changed", sorted(set(changed)) elif unchanged: state, evidence = "unchanged", unchanged else: state, evidence = None, [] unique = {} for event in events: key = (event["object"], event["action"], event["location"], event["relation"]) unique.setdefault(key, event) return { "state": state, "state_evidence": evidence, "events": list(unique.values()), "unresolved": unresolved, "empty": False, }
def event_key(event): return ( event["object"], event["action"], event.get("location") or event.get("region") or None, event.get("relation") or None, )
def prepare_row(row): """Combine verified legacy positives and negatives while retaining unknowns.""" output = { "train_index": int(row["train_index"]), "name": row.get("name"), "changeflag": int(row["changeflag"]), "events": [], } verified = set(row.get("verified_fact_ids", ())) for fact in row.get("facts", ()): if fact["id"] in verified and fact.get("object") in OBJECTS and fact.get("action"): output["events"].append({ **deepcopy(fact), "location": fact.get("region"), "status": "confirmed", "source": fact.get("source") or "legacy_verified_fact_ids", "legacy_fact_id": fact["id"], }) verified_negatives = set(row.get("verified_negative_event_ids", ())) for fact in row.get("negative_events", ()): if fact["id"] in verified_negatives: output["events"].append({ **deepcopy(fact), "status": "absent", "source": fact.get("source") or "legacy_verified_negative_event_ids", }) output["events"].extend(deepcopy(row.get("events", ()))) grouped = {} for event in output["events"]: assert event["status"] in ("confirmed", "absent", "unknown") assert event.get("source") or event["status"] == "unknown" records = event.get("conflicting_records", [event]) grouped.setdefault(event_key(event), []).extend(records) output["events"] = [] for records in grouped.values(): statuses = {record["status"] for record in records} - {"unknown"} if len(statuses) > 1: selected = { **records[-1], "status": "unknown", "conflicting_records": records, } else: status = next(iter(statuses), "unknown") selected = next(record for record in reversed(records) if record["status"] == status) output["events"].append(selected) # A verified local event implies its global existential event. Conflicting # global absence is therefore unresolved instead of penalizing a true claim. for absent in output["events"]: if absent["status"] != "absent": continue conflicts = [ positive for positive in output["events"] if positive["status"] == "confirmed" and event_credit(absent, positive, require_location=True) == 1. ] if conflicts: absent["status"] = "unknown" absent["conflict_reason"] = "verified_positive_implies_event_presence" return output
def event_credit(target, extracted, require_location=False): if target["object"] != extracted["object"] or target["action"] != extracted["action"]: return 0. target_region = target.get("location") or target.get("region") actual_region = extracted.get("location") target_relation, actual_relation = target.get("relation"), extracted.get("relation") if target_region not in (None, "all") and actual_region not in (None, target_region): return 0. if target_relation and actual_relation not in (None, target_relation): return 0. missing_location = ( target_region not in (None, "all") and actual_region is None or target_relation and actual_relation is None ) if require_location and missing_location: return 0. return .75 if missing_location else 1.
def score_caption(caption, row): extracted = extract_caption(caption) expected = "changed" if row["changeflag"] else "unchanged" state = 0. if extracted["state"] is None else 1. if extracted["state"] == expected else -1. confirmed = [event for event in row["events"] if event["status"] == "confirmed"] located_types = { (event["object"], event["action"]) for event in confirmed if event.get("location") not in (None, "all") or event.get("relation") } positives = [ event for event in confirmed if (event["object"], event["action"]) not in located_types or event.get("location") not in (None, "all") or event.get("relation") ] negatives = [event for event in row["events"] if event["status"] == "absent"] credits = [ max((event_credit(event, claim) for claim in extracted["events"]), default=0.) for event in positives ] contradicted = [ event for event in negatives if any( event_credit(event, claim, require_location=True) == 1. for claim in extracted["events"] ) ] unknown_claims = [ claim for claim in extracted["events"] if not any( event_credit(event, claim, require_location=True) == 1. for event in positives + negatives ) ] coverage = sum(credits) / len(positives) if positives else 0. state_weight = .2 if positives else 1. penalty = float(bool(contradicted)) reward = state_weight * state + (1 - state_weight) * coverage - penalty return reward, { "reward": reward, "state_score": state, "state_weight": state_weight, "event_coverage": coverage, "positive_events": len(positives), "positive_credits": credits, "contradicted_events": contradicted, "negative_penalty": penalty, "unknown_claims": unknown_claims, "extraction": extracted, }
class EventReward: def __init__(self, rows): self.rows = {} for row in rows: prepared = prepare_row(row) if prepared["train_index"] in self.rows: raise ValueError("Duplicate train index in event bank") self.rows[prepared["train_index"]] = prepared
def score(self, train_index, caption): return score_caption(caption, self.rows[int(train_index)])
def checks(): row = { "train_index": 0, "changeflag": 1, "events": [ {"id": "build", "object": "building", "action": "added", "status": "confirmed", "source": "fixture"}, {"id": "road", "object": "road", "action": "added", "status": "confirmed", "source": "fixture"}, {"id": "demolish", "object": "building", "action": "removed", "status": "absent", "source": "fixture"}, ], } reward = EventReward([row]) tests = []
def check(name, passed): tests.append({"name": name, "passed": bool(passed)}) assert passed, name
good = reward.score(0, "many houses are built around the lake")[0] bad = reward.score(0, "villas are removed and a road appear on bareland")[0] check("confirmed_false_event_loses_to_correct_partial", good > bad) check("object_alone_earns_no_event_credit", reward.score(0, "houses were removed")[1]["event_coverage"] == 0.) check("reduced_relative_binds_houses", extract_caption("a road with houses built along the road")["events"][0]["object"] == "building") check("finite_verb_preserves_main_subject", extract_caption("a road with houses was built")["events"][0]["object"] == "road") check("trailing_unknown_keeps_completed_event", reward.score(0, "many houses are built around the lake <UNK>")[0] == good) vegetation = extract_caption("trees have been removed and houses have been built")["events"] check("vegetation_and_building_actions_bound", {(event["object"], event["action"]) for event in vegetation} == {("vegetation", "removed"), ("building", "added")}) transition = extract_caption("vegetation was replaced by houses")["events"] check("transition_direction", {(event["object"], event["action"]) for event in transition} == {("vegetation", "removed"), ("building", "added")}) unknown = deepcopy(row) unknown["events"][-1]["status"] = "unknown" unknown_reward = EventReward([unknown]) check("unknown_event_has_zero_penalty", unknown_reward.score(0, "houses were removed")[1]["negative_penalty"] == 0.) check("unknown_addition_cannot_borrow_object_credit", unknown_reward.score(0, "villas were removed and a road appeared")[0] == good) located = deepcopy(row) located["events"] = [{ "id": "left_building", "object": "building", "action": "added", "location": "left", "status": "confirmed", "source": "fixture", }] located_reward = EventReward([located]) check("wrong_event_cannot_supply_location", located_reward.score( 0, "houses were built on the right and roads appeared on the left", )[1]["event_coverage"] == 0.) check("partial_location_gets_partial_credit", located_reward.score(0, "houses were built")[1]["event_coverage"] == .75) check("full_location_gets_full_credit", located_reward.score(0, "houses were built on the left")[1]["event_coverage"] == 1.) check("duplicate_claim_does_not_increase_score", reward.score( 0, "houses were built and houses were built", )[0] == reward.score(0, "houses were built")[0]) located["events"].append(deepcopy(row["events"][0])) check("atomic_and_located_fact_count_once", EventReward([located]).score( 0, "houses were built on the left", )[1]["positive_events"] == 1) conflict = deepcopy(row) conflict["events"] = [ row["events"][0], {**row["events"][0], "status": "absent"}, row["events"][0], ] check("conflict_is_order_independent", prepare_row(conflict)["events"][0]["status"] == "unknown") check("conflict_survives_repeated_preparation", prepare_row( prepare_row(conflict), )["events"][0]["status"] == "unknown") for template in legacy.NC_TEMPLATES: check("true_NC_" + template, score_caption( template, {"changeflag": 0, "events": []}, )[0] == 1.) check("false_NC_" + template, reward.score(0, template)[0] < 0.) return tests123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Auditable clause-level parser and evidence-conditioned costs (no model calls)."""import re
ENT=re.compile(r'\b(buildings?|houses?|villas?|bungalows?|roads?|streets?|highways?|crossroads?)\b')ROAD=re.compile(r'^(?:road|street|highway|crossroad)s?$')ADD=r'built|constructed|added|appears?|appeared|emerged|shows? up|showed up|paved'REMOVE=r'removed|demolished|destroyed|disappears?|disappeared|vanished'MODIFY=r'widened|extended|expanded|narrowed|reduced|changed'VERB=re.compile(r'\b(?:'+ADD+'|'+REMOVE+'|'+MODIFY+r'|replaced by|replaces?|replaced|turned into|turns? into)\b')CONTEXT=re.compile(r'\b(?:with|along|alongside|beside|near|around|between|behind|in front of|on (?:both|either) sides? of)\b')GLOBAL_NO=re.compile(r'\b(?:no (?:significant |obvious |visible |new )?(?:changes?|differences?)|nothing (?:has |is )?changed|nothing changes|same as before)\b|\b(?:scene|images?|area)\b.{0,20}\bunchanged\b')
def location(text): text=CONTEXT.split(text,maxsplit=1)[0] left=bool(re.search(r'\bleft\b',text));right=bool(re.search(r'\bright\b',text)) top=bool(re.search(r'\b(?:upper|top)\b',text));bottom=bool(re.search(r'\b(?:lower|bottom)\b',text)) if left and right or top and bottom:return 'all' if top and left:return 'top_left' if top and right:return 'top_right' if bottom and left:return 'bottom_left' if bottom and right:return 'bottom_right' for flag,name in [(left,'left'),(right,'right'),(top,'top'),(bottom,'bottom')]: if flag:return name if re.search(r'\b(?:centre|center|middle)\b',text):return 'center' return 'all'
def parse(text): sentence=re.sub(r'[^a-z ,.;-]',' ',text.lower());sentence=re.sub(r'\s+',' ',sentence).strip() claims=set();unknown=False;positive_predicates=0 for clause in re.split(r'[.;]|\b(?:while|but)\b',sentence): verbs=list(VERB.finditer(clause));last=0 for i,verb in enumerate(verbs): prefix=clause[last:verb.start()].strip();end=verbs[i+1].start() if i+1<len(verbs) else len(clause) suffix=clause[verb.end():end] if last or re.search(r'\bunchanged\b',prefix):prefix=prefix.rsplit(' and ',1)[-1] prefix=re.sub(r'^(?:and|along|alongside|beside|near|with)\s+','',prefix) subject=CONTEXT.split(prefix,maxsplit=1)[0] tail=re.split(r'\b(?:and|while|but)\b',suffix,maxsplit=1)[0] neg=bool(re.search(r'\b(?:no|not|never|without)\b',subject)) action=verb.group();loc=location(subject+' '+tail) left=list(ENT.finditer(subject));right=[] transitions=action in {'replaced by','turned into','turn into','turns into','replace','replaces','replaced'} if transitions: # Keep coordinated resulting objects; stop only at a new clause # with its own finite predicate, rather than every "and". transition_tail=re.split(r'\band\b(?=.{0,35}\b(?:is|are|was|were|has|have)\b)',suffix,maxsplit=1)[0] right=list(ENT.finditer(CONTEXT.split(transition_tail,maxsplit=1)[0])) if not left and not transitions and re.search(r'\b(?:newly|new)\s*$',subject): right=list(ENT.finditer(CONTEXT.split(tail,maxsplit=1)[0]));left=right if not neg: positive_predicates+=1 if transitions: passive=action=='replaced by' or 'into' in action for mentions,direction in [(left,'disappear' if passive else 'appear'),(right,'appear' if passive else 'disappear')]: for item in mentions:claims.add(('1' if ROAD.fullmatch(item.group()) else '2',direction,loc)) unknown|=not bool(left or right) else: direction='appear' if re.fullmatch(ADD,action) else 'disappear' if re.fullmatch(REMOVE,action) else 'change' for item in left:claims.add(('1' if ROAD.fullmatch(item.group()) else '2',direction,loc)) unknown|=not bool(left) last=verb.end() return dict(claims=[dict(category=c,action=a,location=r) for c,a,r in sorted(claims)], no_change=bool(GLOBAL_NO.search(sentence)) and positive_predicates==0, unknown=unknown,has_change_predicate=positive_predicates>0)
def semantic_cost(text,evidence,weights=None): """Unknown evidence abstains; costs cannot infer direction from a union mask.""" parsed=parse(text);contradictions=[];direction=[];spatial=[] for claim in parsed['claims']: c=claim['category'];item=evidence.get('categories',{}).get(c,{}) if item.get('changed_state')==-1:contradictions.append(1.) elif item.get('changed_state')==1:contradictions.append(0.) if item.get('direction_verified') and claim['action'] in {'appear','disappear'}: known=item.get(claim['action']+'_state',0) if known:direction.append(float(known==-1)) if claim['location']!='all' and item.get('spatial_verified'): known=item.get('locations',{}).get(claim['location'],0) if known:spatial.append(float(known==-1)) h=max(contradictions,default=0.) d=max(direction,default=0.);p=max(spatial,default=0.) state=float(parsed['no_change'] and evidence.get('reliable_change',False)) return dict(object=h,direction=d,location=p,state=state)
def scalar_cost(cost,weights):return sum(cost[k]*weights.get(k,0.) for k in cost)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465"""Frozen caption-only QA extraction and fixed-denominator reward.
The extractor sees caption text and neutral event selectors. Expected answersare used only by score_caption. The closed grammar deliberately abstains whenan event or its location cannot be bound reliably."""from __future__ import annotations
from collections import Counterfrom copy import deepcopyimport re
from . import legacy_event_parse as _legacy
NC_TEMPLATES = ( "there is no difference", "the two scenes seem identical", "the scene is the same as before", "no change has occurred", "almost nothing has changed",)OBJECTS = {"1": "road", "2": "building"}ACTIONS = {"appear": "added", "disappear": "removed", "change": "other"}STATE_QUESTION = { "id": "state", "type": "state", "text": "Does the caption report a structural change?", "choices": ["changed", "unchanged", "unmentioned"],}_SPATIAL = re.compile(r"\b(?:left|right|top|upper|bottom|lower|centre|center|middle)\b")_UNCERTAIN = re.compile( r"\b(?:not|never|without|no|may|might|could|would|should|perhaps|maybe)\b" r"|\b(?:seems?|appears?)\s+to\b")_EXTRA_CONTEXT = re.compile(r"\b(?:by|next to|adjacent to|close to|surrounded by)\b")_LANDMARK = re.compile( r"\b(?:in|on|at|to|of|for)\s+" r"(?:(?:a|an|the|some|new|old|wide|small|large)\s+){0,4}" + _legacy.ENT.pattern)_RELATIVE = re.compile( r"\b(?:left|right|top|upper|bottom|lower|centre|center|middle)\b" r"(?:\s+(?:side|part|region|corner))?\s+of\s+" r"(?:(?:a|an|the|some|new|old|wide|small|large)\s+){0,4}" + _legacy.ENT.pattern)_GENERIC_CHANGE = re.compile( r"^(?:the\s+)?(?:scene|images?|area)\s+(?:has|have)\s+changed$" r"|^(?:some|several|many|a few)\s+(?:structural\s+)?changes?\s+" r"(?:have|has)\s+(?:occurred|appeared)$")
def _normalize(text): return re.sub(r"\s+", " ", text.lower().replace("-", " ")).strip(" .,!;")
def _subject_core(text): """Stop before contextual landmarks, preserving full-image directions.""" cuts = [ match.start() for pattern in (_legacy.CONTEXT, _EXTRA_CONTEXT, _LANDMARK) if (match := pattern.search(text)) ] return text[:min(cuts)] if cuts else text
def _targets(text): core = _subject_core(text) mentions = list(_legacy.ENT.finditer(core)) for first, second in zip(mentions, mentions[1:]): if not re.search(r"\band\b|,", core[first.end():second.start()]): return [], core objects = sorted({ "road" if _legacy.ROAD.fullmatch(mention.group()) else "building" for mention in mentions }) return objects, core
def _clauses(text): """Split separate predicates without splitting coordinated object nouns.""" output = [] for clause in re.split(r"[.;]|\b(?:while|but)\b", text): verbs = list(_legacy.VERB.finditer(clause)) boundaries = [] for first, second in zip(verbs, verbs[1:]): gap = clause[first.end():second.start()] joins = list(re.finditer(r"\band\b|,", gap)) for join in reversed(joins): tail = gap[join.end():] if _legacy.ENT.search(tail): boundaries.append(first.end() + join.start()) break start = 0 for end in boundaries: output.append(clause[start:end].strip(" ,")) join = re.match(r"(?:and\b|,)\s*", clause[end:]) start = end + len(join.group()) output.append(clause[start:].strip(" ,")) return [re.sub(r"^and\s+", "", item) for item in output if item]
def _event_location(prefix, suffix): if _RELATIVE.search(prefix + " " + suffix): return None, "abstained" prefix, suffix = _subject_core(prefix), _subject_core(suffix) text = prefix + " " + suffix region = _legacy.location(text) if region != "all": return region, "answered" return None, "abstained" if _SPATIAL.search(text) else "missing"
def _parse_clause(clause): """Return explicit bound events, leaving unclear syntax unresolved.""" if re.search(r"<[^>]*>|[?]", clause) or _UNCERTAIN.search(clause): return [], "uncertain_or_malformed_clause" verbs = list(_legacy.VERB.finditer(clause)) if len(verbs) != 1: return [], "unrecognized_predicate" verb = verbs[0] prefix, suffix = clause[:verb.start()], clause[verb.end():] subjects, subject_core = _targets(prefix) action = verb.group() transition = action in { "replaced by", "turned into", "turn into", "turns into", "replace", "replaces", "replaced", } if transition: results, result_core = _targets(suffix) if not subjects or not results: return [], "unresolved_transition" passive = action == "replaced by" or "into" in action sides = [ (subjects, "removed" if passive else "added"), (results, "added" if passive else "removed"), ] region, location_status = _event_location(prefix, suffix) else: if not subjects and re.search(r"\b(?:new|newly)\s*$", prefix): subjects, subject_core = _targets(suffix) prefix = "" if not subjects: return [], "unrecognized_event_subject" # Reuse the legacy action inventory only after target and scope checks. parsed = _legacy.parse(subject_core + " " + action) categories = {claim["action"] for claim in parsed["claims"]} if len(categories) != 1: return [], "unrecognized_event_action" sides = [(subjects, ACTIONS[categories.pop()])] region, location_status = _event_location(prefix, suffix) events = [ { "object": obj, "action": direction, "location": region, "location_status": location_status, "evidence": clause, } for objects, direction in sides for obj in objects ] return events, None
def extract_caption(caption): """Extract evidence using only caption text, with no image or truth inputs.""" if not isinstance(caption, str) or not caption.strip(): return { "state": None, "state_evidence": [], "events": [], "unresolved": [], "empty": True, } text = _normalize(caption) # These five dataset templates must precede the legacy predicate parser. if text in NC_TEMPLATES: return { "state": "unchanged", "state_evidence": [caption.strip()], "events": [], "unresolved": [], "empty": False, } if "?" in text: return { "state": None, "state_evidence": [], "events": [], "unresolved": [{"text": text, "reason": "question_only_or_question_text"}], "empty": False, } events, unchanged, generic, unresolved = [], [], [], [] for clause in _clauses(text): if clause in NC_TEMPLATES or ( _legacy.GLOBAL_NO.search(clause) and not _legacy.ENT.search(clause) ): unchanged.append(clause) continue if _GENERIC_CHANGE.fullmatch(clause): generic.append(clause) continue found, reason = _parse_clause(clause) events.extend(found) if reason: unresolved.append({"text": clause, "reason": reason}) changed = [item["evidence"] for item in events] + generic if changed and unchanged: state, evidence = None, [] unresolved.append({"text": text, "reason": "conflicting_change_state"}) elif changed: state, evidence = "changed", sorted(set(changed)) elif unchanged: state, evidence = "unchanged", unchanged else: state, evidence = None, [] return { "state": state, "state_evidence": evidence, "events": events, "unresolved": unresolved, "empty": False, }
def _bind_selectors(row, questions): facts = {fact["id"]: fact for fact in row.get("facts", [])} bound = deepcopy(questions) for question in bound: if question["type"] != "location": continue fact = facts.get(question.get("requires", "location"), {}) if fact: question.setdefault("subject", fact.get("object")) question.setdefault("selector_action", fact.get("action")) return bound
def prepare_question_bank(row, verified_fact_ids): """Freeze eligible questions before scoring any candidate caption.
State is label-derived. Detailed questions require independently verified fact IDs. A location selector names the object and event being asked about. """ verified = set(verified_fact_ids) questions = [ question for question in row.get("questions", []) if question["type"] == "state" or question.get("requires") in verified ] if "changeflag" in row: if row["changeflag"] not in (0, 1): raise ValueError("changeflag must be 0 or 1") answer = "changed" if row["changeflag"] else "unchanged" states = [question for question in questions if question["type"] == "state"] if states and any(question.get("answer") != answer for question in states): raise ValueError("State answer disagrees with changeflag") if not states: questions.insert(0, { **deepcopy(STATE_QUESTION), "answer": answer, "source": "LEVIR-CC changeflag", }) if not row["changeflag"]: questions = [question for question in questions if question["type"] == "state"] ids = [question["id"] for question in questions] if len(ids) != len(set(ids)): raise ValueError("Question IDs must be unique within an image") return _bind_selectors(row, questions)
def answer_question(extraction, selector): """Return evidence-bound answer sets without consulting expected answers.""" kind = selector["type"] events = extraction["events"] if kind == "state": answers = [extraction["state"]] if extraction["state"] else [] evidence = extraction["state_evidence"] elif kind == "object": answers = sorted({event["object"] for event in events}) evidence = [event["evidence"] for event in events] elif kind in {"action", "location"}: subject = selector.get("subject") events = [event for event in events if event["object"] == subject] if not subject: return {"answers": [], "evidence": [], "status": "abstained", "reason": "missing_object_selector"} if kind == "action": answers = sorted({event["action"] for event in events}) else: action = selector.get("selector_action") if not action: return {"answers": [], "evidence": [], "status": "abstained", "reason": "missing_event_selector"} events = [event for event in events if event["action"] == action] answers = sorted({event["location"] for event in events if event["location"]}) evidence = [event["evidence"] for event in events if kind != "location" or event["location"]] else: return {"answers": [], "evidence": [], "status": "abstained", "reason": "unsupported_question_type"} if answers: return {"answers": answers, "evidence": sorted(set(evidence)), "status": "answered"} ambiguous_location = kind == "location" and any( event["location_status"] == "abstained" for event in events ) status = "abstained" if extraction["unresolved"] or ambiguous_location else "missing" return {"answers": [], "evidence": [], "status": status}
def score_caption(caption, bank): """Return (mean correct, details), using the same bank for every candidate.""" extraction = extract_caption(caption) questions, counts = [], Counter(correct=0, wrong=0, missing=0, abstained=0) for question in bank: # Neither the answer nor reference metadata reaches answer_question. selector = {key: question[key] for key in ("id", "type", "subject", "selector_action") if key in question} extracted = answer_question(extraction, selector) expected = question["answer"] if expected in extracted["answers"]: outcome = "correct" elif extracted["answers"]: outcome = "wrong" else: outcome = extracted["status"] counts[outcome] += 1 questions.append({ "id": question["id"], "type": question["type"], **extracted, "expected": expected, "outcome": outcome, }) reward = counts["correct"] / len(bank) if bank else 0.0 return reward, { "reward": reward, "question_count": len(bank), "outcomes": dict(counts), "questions": questions, "extraction": extraction, }
class QAReward: """Online SCST adapter for frozen per-image rows keyed by train_index."""
def __init__(self, bank_rows): self.banks = {} for row in bank_rows: index = int(row["train_index"]) if index in self.banks: raise ValueError(f"Duplicate train_index {index}") # Pre-filtered banks may omit verification metadata. Raw B0 rows # should provide verified_fact_ids or call prepare_question_bank. if "verified_fact_ids" in row: verified = row["verified_fact_ids"] else: verified = {question.get("requires") for question in row.get("questions", [])} self.banks[index] = prepare_question_bank(row, verified)
def score(self, train_index, caption): index = int(train_index) reward, details = score_caption(caption, self.banks.get(index, ())) details["train_index"] = index details["bank_index_present"] = index in self.banks return reward, details
def _checks(): state = {**STATE_QUESTION, "answer": "unchanged"} row = { "train_index": 4, "changeflag": 1, "facts": [ {"id": "event", "object": "building", "action": "added"}, {"id": "location", "object": "building", "action": "added", "region": "left"}, ], "questions": [ {**STATE_QUESTION, "answer": "changed"}, {"id": "object", "type": "object", "requires": "event", "answer": "building"}, {"id": "action", "type": "action", "requires": "event", "subject": "building", "answer": "added"}, {"id": "location", "type": "location", "requires": "location", "subject": "building", "answer": "left"}, ], } bank = prepare_question_bank(row, {"event", "location"}) checks = []
def check(name, actual, expected): checks.append({"name": name, "passed": actual == expected, "actual": actual, "expected": expected})
def summary(caption): reward, details = score_caption(caption, bank) return {"reward": reward, **details["outcomes"]}
for template in NC_TEMPLATES: check("nc_template_" + template.replace(" ", "_"), score_caption(template.upper() + " . ", [state])[0], 1.0) for name, caption in (("none", None), ("empty", ""), ("spaces", " ")): check("absent_caption_" + name, score_caption(caption, bank)[0], 0.0) check("question_only", score_caption(STATE_QUESTION["text"], bank)[0], 0.0) check("complete", summary("a house was built on the left"), {"reward": 1.0, "correct": 4, "wrong": 0, "missing": 0, "abstained": 0}) check("partial", summary("a house was built"), {"reward": .75, "correct": 3, "wrong": 0, "missing": 1, "abstained": 0}) check("opposite_action", summary("a house was removed on the left"), {"reward": .5, "correct": 2, "wrong": 1, "missing": 1, "abstained": 0}) check("opposite_location", summary("a house was built on the right"), {"reward": .75, "correct": 3, "wrong": 1, "missing": 0, "abstained": 0}) check("coordinated_targets", sorted({ event["object"] for event in extract_caption("houses and roads built")["events"] }), ["building", "road"]) check("partial_multiobject_credit", score_caption("houses and roads built", bank)[0], .75) check("contextual_road_not_target", sorted({ event["object"] for event in extract_caption("a house was built along a road")["events"] }), ["building"]) check("contextual_houses_not_target", sorted({ event["object"] for event in extract_caption("a road with houses was built")["events"] }), ["road"]) check("landmark_direction_not_event_location", score_caption("a house was built near a road on the left", bank)[0], .75) check("relative_location_not_global_location", score_caption("a house was built to the left of a road", bank)[0], .75) check("relative_subject_location_not_global_location", score_caption("a house to the left of a road was built", bank)[0], .75) check("nearby_landmark_direction_not_event_location", score_caption("a house was built next to a road on the left", bank)[0], .75) check("full_image_location_retained", score_caption("a house on the left side of the image was built", bank)[0], 1.0) check("postpositive_event_and_location", score_caption("there are newly built houses on the left", bank)[0], 1.0) mixed = "houses were built on the left and houses were removed on the right" check("mixed_events", [ [event["object"], event["action"], event["location"]] for event in extract_caption(mixed)["events"] ], [["building", "added", "left"], ["building", "removed", "right"]]) check("mixed_events_added_location", score_caption(mixed, bank)[0], 1.0) removed_right = deepcopy(bank[-1]) removed_right.update(selector_action="removed", answer="right") check("mixed_events_removed_location", score_caption(mixed, [removed_right])[0], 1.0) added_right = deepcopy(bank[-1]) added_right["answer"] = "right" check("no_location_borrowed_from_other_event", score_caption(mixed, [added_right])[0], 0.0) check("malformed_clause", score_caption("houses <UNK> built on the left", bank)[0], 0.0) check("uncoordinated_targets_abstain", score_caption("houses roads built on the left", bank)[0], 0.0) check("noun_only_abstains", score_caption("new houses on the left", bank)[0], 0.0) check("uncertain_claim_abstains", score_caption("houses might be built on the left", bank)[0], 0.0) original_answers = score_caption("houses built on the left", bank)[1]["questions"] altered = deepcopy(bank) for question in altered: question["answer"] = "incorrect_control" altered_answers = score_caption("houses built on the left", altered)[1]["questions"] check("expected_answer_does_not_reach_extractor", [record["answers"] for record in altered_answers], [record["answers"] for record in original_answers]) reordered = deepcopy(bank) for question in reordered: question["choices"] = list(reversed(question.get("choices", ["a", "b"]))) check("option_order_invariant", score_caption("houses built on the left", reordered)[0], 1.0) check("fixed_denominator", [ score_caption(caption, bank)[1]["question_count"] for caption in ("", "houses built", "houses built on the left") ], [4, 4, 4]) check("extra_detail_does_not_increase_reward", score_caption("houses built on the left and roads removed on the right", bank)[0], score_caption("houses built on the left", bank)[0]) check("unverified_facts_excluded", len(prepare_question_bank(row, set())), 1) adapter = QAReward([row, {"train_index": 8, "changeflag": 0}]) check("online_adapter", adapter.score(4, "houses built on the left")[0], 1.0) check("state_derived_for_alltrain_row", adapter.score(8, NC_TEMPLATES[1])[0], 1.0) check("no_bank_index_zero_extra", adapter.score(999, "houses built on the left")[0], 0.0) check("no_bank_denominator_zero", adapter.score(999, "houses built")[1]["question_count"], 0) return checks
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Caption-only QA revision with verified contradiction penalties."""from __future__ import annotations
from collections import Counterimport re
from . import qa_reward as base
_ROW_GROUP = re.compile( r"\b(?:rows?|lines?)\s+of\s+(?=(?:new\s+)?" r"(?:buildings?|houses?|villas?|bungalows?|roads?|streets?|highways?|crossroads?)\b)")_CONTEXT_MODIFIER = re.compile( r"\b(?P<context>with|along|alongside|beside|near|around|between|behind|" r"in front of|next to|adjacent to)\s+" r"(?P<determiners>(?:(?:a|an|the|some|many|several)\s+)?)" r"newly\s+(?:built|constructed)\s+" r"(?=(?:buildings?|houses?|villas?|bungalows?|roads?|streets?|highways?|crossroads?)\b)")_STATE_ENTITY = re.compile( r"\b(?:buildings?|houses?|villas?|bungalows?|roads?|streets?|highways?|crossroads?|" r"parking lots?|residential areas?|trees?|plants?|vegetation|forests?|woods?|" r"bareland|farmland)\b")
def _canonical_clause(clause): clause = _ROW_GROUP.sub("", clause) clause = re.sub(r"\berected\b", "constructed", clause) return _CONTEXT_MODIFIER.sub( lambda match: match["context"] + " " + match["determiners"] + "new ", clause, )
def extract_caption(caption): """Retain original evidence while normalizing known equivalent phrases.""" if not isinstance(caption, str) or not caption.strip(): return base.extract_caption(caption) original = base._normalize(caption) if original in base.NC_TEMPLATES or "?" in original: return base.extract_caption(caption) clauses = base._clauses(original) evidence = {_canonical_clause(clause): clause for clause in clauses} extraction = base.extract_caption(" ; ".join(evidence)) for event in extraction["events"]: event["evidence"] = evidence.get(event["evidence"], event["evidence"]) extraction["state_evidence"] = [ evidence.get(text, text) for text in extraction["state_evidence"] ] for unresolved in extraction["unresolved"]: unresolved["text"] = evidence.get(unresolved["text"], unresolved["text"])
# State recognition also covers explicit changes outside the detail grammar. additional = [] for canonical, original_clause in evidence.items(): if base._UNCERTAIN.search(canonical) or re.search(r"<[^>]*>|[?]", canonical): continue verbs = list(base._legacy.VERB.finditer(canonical)) if len(verbs) != 1: continue verb = verbs[0] subject = base._subject_core(canonical[:verb.start()]) if _STATE_ENTITY.search(subject): additional.append(original_clause) if additional and extraction["state"] != "unchanged": extraction["state"] = "changed" extraction["state_evidence"] = sorted(set(extraction["state_evidence"] + additional)) return extraction
def score_caption(caption, bank, contradiction_penalty=.5): """Score coverage and separately penalize explicitly verified contradictions.""" extraction = extract_caption(caption) counts = Counter(correct=0, wrong=0, missing=0, abstained=0) questions = [] for question in bank: selector = {key: question[key] for key in ("id", "type", "subject", "selector_action") if key in question} extracted = base.answer_question(extraction, selector) expected = question["answer"] negatives = set(question.get("verified_negative_answers", ())) if question["type"] == "state" and expected in {"changed", "unchanged"}: negatives.add("unchanged" if expected == "changed" else "changed") contradicted = sorted(negatives.intersection(extracted["answers"])) if contradicted: outcome = "contradicted" elif expected in extracted["answers"]: outcome = "correct" elif extracted["answers"]: outcome = "wrong" else: outcome = extracted["status"] counts[outcome] += 1 questions.append({ "id": question["id"], "type": question["type"], **extracted, "expected": expected, "outcome": outcome, "verified_contradicted_answers": contradicted, }) numerator = counts["correct"] - contradiction_penalty * counts["contradicted"] reward = numerator / len(bank) if bank else 0. return reward, { "reward": reward, "question_count": len(bank), "outcomes": dict(counts), "questions": questions, "extraction": extraction, }
class QAReward(base.QAReward): """Reuse the frozen bank construction and the existing online adapter API."""
def score(self, train_index, caption): index = int(train_index) reward, details = score_caption(caption, self.banks.get(index, ())) details["train_index"] = index details["bank_index_present"] = index in self.banks return reward, details1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Build the paper's reference-free ranking prompts from candidate captions."""
import hashlibimport jsonimport re
from pipeline import next_stage, unchangedfrom .event_reward_v7 import extract_caption
CHRONOLOGY = 'T1 is the earlier image: <image:1>\nT2 is the later image of the same location: <image:2>'GENERAL = ( 'Given the bi-temporal remote sensing images, which of the following descriptions ' 'most accurately and correctly captures the actual land-cover change? ' 'Judge the object, temporal action, location, and whether change actually occurred. ' 'If all descriptions contain errors, select the one best supported by the images with the fewest unsupported claims.')CHANGED = ( 'All listed captions describe a physical change between the earlier image T1 and ' 'the later image T2. Which caption most accurately and completely describes the ' 'visible changes, including the changed objects, temporal actions, and spatial ' 'relations? Prefer the caption with the fewest unsupported claims. Select one option.')
def signature(*values): raw = json.dumps(values, ensure_ascii=False, separators=(',', ':')) return hashlib.sha256(raw.encode('utf-8')).hexdigest()[:24]
def stage1_order(dataset, name, count): indices = range(count) if dataset == 'dubai': return sorted(indices, key=lambda index: signature('dubai-rank17', name, index)) return list(indices)
def stage2_order(dataset, name, captions, templates): if dataset == 'dubai': return [index for index in stage1_order(dataset, name, len(captions)) if captions[index].strip() and not unchanged(dataset, captions[index], templates) and not re.match(r'^(?:no changes?\b|nothing (?:has )?changed\b)', captions[index])] seen = set(templates) keep = [] for index, text in enumerate(captions): if text in seen or (dataset == 'whu' and not text) or extract_caption(text)['state'] == 'unchanged': continue seen.add(text) keep.append(index) salt = 'exp1-pool-order-17' if dataset == 'levir' else 'whu-specialist-order-17' return sorted(keep, key=lambda index: signature(salt, name, index))
def question(dataset, row, captions, indices, stage): named = stage == 1 or dataset == 'dubai' prefix = 'caption' if named else 'item' mapping = {f'{prefix}_{position}': index for position, index in enumerate(indices, 1)} size = 50 if dataset == 'dubai' else 256 return { 'name': row['name'], 'task': 'beam_caption_choice', 'state': CHRONOLOGY, 'question': {'type': 'choice', 'instructions': GENERAL if named else CHANGED, 'criteria': {label: captions[index] for label, index in mapping.items()}}, 'native_candidate_indices': mapping, 'target': {label: 1 / len(indices) for label in mapping}, 'weight': 1.0, 'media': [{'type': 'image', 'path': path, 'h': size, 'w': size} for path in row['media']], }
def stage1_questions(dataset, metadata, rows): for row in metadata: captions = rows[row['name']]['captions'] yield question(dataset, row, captions, stage1_order(dataset, row['name'], len(captions)), 1)
def stage2_questions(dataset, metadata, rows, templates): for row in metadata: record = rows[row['name']] captions = record['captions'] anchor = max(record['stage1'], key=lambda pair: pair[1])[0] _, routed = next_stage(dataset, captions, anchor, templates) indices = stage2_order(dataset, row['name'], captions, templates) if routed else [] record['stage2'] = [[indices[0], 1.0]] if len(indices) == 1 else [] if len(indices) > 1: yield question(dataset, row, captions, indices, 2)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Load a pinned Elephant runtime and score ordered decision slots."""
from functools import partialimport hashlibimport importlibimport os
def setup(): import torch import torch.distributed as dist
rank = int(os.environ.get('RANK', '0')) world = int(os.environ.get('WORLD_SIZE', '1')) if world > 1: devices = os.environ.get('CUDA_VISIBLE_DEVICES') if devices is None: devices = ','.join(str(index) for index in range(torch.cuda.device_count())) os.environ['CUDA_VISIBLE_DEVICES'] = devices.split(',')[int(os.environ['LOCAL_RANK'])] dist.init_process_group('nccl', device_id=torch.device('cuda:0')) elif not torch.cuda.is_available(): raise RuntimeError('Elephant NF4/BF16 inference and training require CUDA.') return rank, world
def load(dataset, stage, base_dir, image_root, adapter, **kwargs): runtime = importlib.import_module(f'judge.stage{stage}_runtime') from qev.prompt import PromptStyle, render_question
runtime.common.render_question = partial(render_question, style=PromptStyle(show_names=stage == 1 or dataset == 'dubai')) bundle, _ = runtime.load_model(base_dir, image_root, adapter=adapter, **kwargs) return runtime, bundle
def score(runtime, bundle, questions, rank=0, world=1): import torch.distributed as dist
questions = list(questions) local = [row for row in questions if int(hashlib.sha256(row['name'].encode()).hexdigest(), 16) % world == rank] bundle.model.eval() results = {} for offset in range(0, len(local), 4): chunk = local[offset:offset + 4] for row, scores in zip(chunk, runtime.predict(bundle, chunk), strict=True): results[row['name']] = [[index, scores[label]] for label, index in row['native_candidate_indices'].items()] if world > 1: shards = [None] * world dist.all_gather_object(shards, results) results = {key: value for shard in shards for key, value in shard.items()} if len(results) != len(questions): raise ValueError('Missing or duplicate question scores') return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Pinned elephant-1 paired-image scoring and language-only QLoRA."""from contextlib import contextmanagerimport hashlibimport jsonfrom pathlib import Pathimport sys
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "vendor/OneJev"))
import torchimport bitsandbytes as bnbfrom peft import PeftModelfrom transformers import AutoConfig, BitsAndBytesConfig, Qwen3_5ForConditionalGeneration
from qev import readoutfrom train import common, mm
def tensor_digest(tensor): data = tensor.detach().cpu().contiguous().view(torch.uint8).numpy().tobytes() return hashlib.sha256(data).hexdigest()
def load_model(base_dir, image_root, adapter=None, seed=17, sdpa_backend="math"): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False torch.backends.cudnn.benchmark = False # The fused SDPA backward varied by 1.1% on this SM120/BF16 stack. # The math kernel gives exact repeated and checkpointed gradient parity. if sdpa_backend not in ("math", "auto"): raise ValueError(f"Unsupported SDPA backend {sdpa_backend}") optimized_attention = sdpa_backend == "auto" torch.backends.cuda.enable_flash_sdp(optimized_attention) torch.backends.cuda.enable_mem_efficient_sdp(optimized_attention) torch.backends.cuda.enable_cudnn_sdp(optimized_attention) torch.backends.cuda.enable_math_sdp(True) torch.set_num_threads(8) mm.set_root(image_root) bundle = common.load_bundle(str(base_dir), multimodal=True, load_model=False) config = AutoConfig.from_pretrained(base_dir, local_files_only=True) if config.modeling_overrides["attention"] != { "full_attention": "block_bidirectional", "linear_attention": "causal", }: raise ValueError("The published attention overrides must be preserved") quantization = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16, llm_int8_skip_modules=["model.visual", "lm_head"], ) model = Qwen3_5ForConditionalGeneration.from_pretrained( base_dir, config=config, dtype=torch.bfloat16, quantization_config=quantization, device_map={"": "cuda:0"}, attn_implementation="sdpa", local_files_only=True, low_cpu_mem_usage=True, ) model.requires_grad_(False) model.config.use_cache = False model.config.get_text_config().use_cache = False bundle.readout = readout.Readout.attach( model, readout.ReadoutConfig.load(base_dir), slot_ids=bundle.slot_ids, ) if adapter is not None: model = PeftModel.from_pretrained(model, adapter, is_trainable=False) bundle.model = model model.eval() base = model.get_base_model() if isinstance(model, PeftModel) else model base.model.visual.eval() assert not any(parameter.requires_grad for parameter in base.model.visual.parameters()) assert not any(isinstance(module, bnb.nn.Linear4bit) for module in base.model.visual.modules()) assert base.get_input_embeddings().weight.dtype == torch.bfloat16 assert base.lm_head.weight.dtype == torch.bfloat16 metadata = { "trainable_parameters": sum(p.numel() for p in model.parameters() if p.requires_grad), "trainable_tensors": sum(p.requires_grad for p in model.parameters()), "quantized_language_linears": sum(isinstance(m, bnb.nn.Linear4bit) for m in model.modules()), "frozen_vision": True, "attention": bundle.readout.config.attention, "sdpa_backend": sdpa_backend, "readout": bundle.readout.config.readout, "memory_allocated": torch.cuda.memory_allocated(), } print("MODEL_LOADED", json.dumps(metadata), flush=True) return bundle, metadata
def prepare_batch(bundle, rows, seed=None): examples = [ common.render_example(row, bundle.template_for(row), index, seed=None if seed is None else seed + index, augment=False) for index, row in enumerate(rows) ] inputs, ends = mm.mm_inputs( bundle.processor, [example.prompt for example in examples], [row["media"] for row in rows], "cuda:0", ) prefixes = [] for example, row, end in zip(examples, rows, ends): ids, prefix, _ = readout.token_layout( bundle.tokenizer, example.prompt, example.suffix_start, example.option_spans, ) shift = bundle.counter.media_extra(row["media"]) if len(ids) + shift != end + 1: raise ValueError("The multimodal token layout does not match the real processor") prefixes.append(prefix + shift) width = inputs["input_ids"].shape[1] if width > 1024: raise ValueError(f"Row exceeds the declared token budget: {width}") block_ids = readout.block_ids(prefixes, [end + 1 for end in ends], width, "cuda:0") kmax = max(len(example.labels) for example in examples) targets = torch.zeros(len(rows), kmax, device="cuda:0") for index, example in enumerate(examples): targets[index, :len(example.target)] = torch.tensor(example.target, device="cuda:0") return { "examples": examples, "inputs": inputs, "ends": ends, "prefixes": prefixes, "block_ids": block_ids, "targets": targets, }
@contextmanagerdef scoring_context(batch, causal=False): # This context stays open during backward as well as forward. with readout.blocks(None if causal else batch["block_ids"]): with torch.autocast("cuda", dtype=torch.bfloat16): yield
def score_batch(bundle, batch): logits = mm.mm_readout_logits(bundle.model, batch["inputs"], batch["ends"]) ks = [len(example.labels) for example in batch["examples"]] return common.slot_view(logits, bundle.slot_ids, ks)
@torch.no_grad()def predict(bundle, rows, seed=None, causal=False): batch = prepare_batch(bundle, rows, seed=seed) with scoring_context(batch, causal=causal): logits, mask = score_batch(bundle, batch) probabilities = logits.softmax(dim=-1).cpu().tolist() return [ {label: probabilities[index][position] for position, label in enumerate(example.labels)} for index, example in enumerate(batch["examples"]) ]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158"""Isolated Elephant language and vision-merger QLoRA runtime."""
from contextlib import contextmanager
import hashlib
import json
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "vendor/OneJev"))
import torch
import bitsandbytes as bnb
from peft import LoraConfig, PeftModel
from transformers import AutoConfig, BitsAndBytesConfig, Qwen3_5ForConditionalGeneration
from qev import readout
from train import common, mm
def tensor_digest(tensor):
data = tensor.detach().cpu().contiguous().view(torch.uint8).numpy().tobytes()
return hashlib.sha256(data).hexdigest()
def load_model(base_dir, image_root, adapter=None, seed=17, sdpa_backend="math"):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cudnn.benchmark = False
# The fused SDPA backward varied by 1.1% on this SM120/BF16 stack.
# The math kernel gives exact repeated and checkpointed gradient parity.
if sdpa_backend not in ("math", "auto"):
raise ValueError(f"Unsupported SDPA backend {sdpa_backend}")
optimized_attention = sdpa_backend == "auto"
torch.backends.cuda.enable_flash_sdp(optimized_attention)
torch.backends.cuda.enable_mem_efficient_sdp(optimized_attention)
torch.backends.cuda.enable_cudnn_sdp(optimized_attention)
torch.backends.cuda.enable_math_sdp(True)
torch.set_num_threads(8)
mm.set_root(image_root)
bundle = common.load_bundle(str(base_dir), multimodal=True, load_model=False)
config = AutoConfig.from_pretrained(base_dir, local_files_only=True)
if config.modeling_overrides["attention"] != {
"full_attention": "block_bidirectional", "linear_attention": "causal",
}:
raise ValueError("The published attention overrides must be preserved")
quantization = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16,
llm_int8_skip_modules=["model.visual", "lm_head"],
)
model = Qwen3_5ForConditionalGeneration.from_pretrained(
base_dir,
config=config,
dtype=torch.bfloat16,
quantization_config=quantization,
device_map={"": "cuda:0"},
attn_implementation="sdpa",
local_files_only=True,
low_cpu_mem_usage=True,
)
model.requires_grad_(False)
model.config.use_cache = False
model.config.get_text_config().use_cache = False
bundle.readout = readout.Readout.attach(
model, readout.ReadoutConfig.load(base_dir), slot_ids=bundle.slot_ids,
)
if adapter is not None:
lora = LoraConfig.from_pretrained(adapter)
vision_targets = ["model.visual.merger.linear_fc1", "model.visual.merger.linear_fc2"]
lora.target_modules = set(lora.target_modules) | set(vision_targets)
model = PeftModel.from_pretrained(
model, adapter, config=lora, is_trainable=False,
)
bundle.model = model
model.eval()
base = model.get_base_model() if isinstance(model, PeftModel) else model
base.model.visual.eval()
assert all(not parameter.requires_grad or "merger." in name and "lora_" in name
for name, parameter in base.model.visual.named_parameters())
assert not any(isinstance(module, bnb.nn.Linear4bit) for module in base.model.visual.modules())
assert base.get_input_embeddings().weight.dtype == torch.bfloat16
assert base.lm_head.weight.dtype == torch.bfloat16
metadata = {
"trainable_parameters": sum(p.numel() for p in model.parameters() if p.requires_grad),
"trainable_tensors": sum(p.requires_grad for p in model.parameters()),
"quantized_language_linears": sum(isinstance(m, bnb.nn.Linear4bit) for m in model.modules()),
"frozen_vision_backbone": True,
"merger_lora_parameters": sum(p.numel() for n, p in model.named_parameters()
if ".visual.merger." in n and "lora_" in n),
"attention": bundle.readout.config.attention,
"sdpa_backend": sdpa_backend,
"readout": bundle.readout.config.readout,
"memory_allocated": torch.cuda.memory_allocated(),
}
print("MODEL_LOADED", json.dumps(metadata), flush=True)
return bundle, metadata
def prepare_batch(bundle, rows, seed=None):
examples = [
common.render_example(row, bundle.template_for(row), index,
seed=None if seed is None else seed + index, augment=False)
for index, row in enumerate(rows)
]
inputs, ends = mm.mm_inputs(
bundle.processor, [example.prompt for example in examples],
[row["media"] for row in rows], "cuda:0",
)
prefixes = []
for example, row, end in zip(examples, rows, ends):
ids, prefix, _ = readout.token_layout(
bundle.tokenizer, example.prompt, example.suffix_start, example.option_spans,
)
shift = bundle.counter.media_extra(row["media"])
if len(ids) + shift != end + 1:
raise ValueError("The multimodal token layout does not match the real processor")
prefixes.append(prefix + shift)
width = inputs["input_ids"].shape[1]
if width > 1024:
raise ValueError(f"Row exceeds the declared token budget: {width}")
block_ids = readout.block_ids(prefixes, [end + 1 for end in ends], width, "cuda:0")
kmax = max(len(example.labels) for example in examples)
targets = torch.zeros(len(rows), kmax, device="cuda:0")
for index, example in enumerate(examples):
targets[index, :len(example.target)] = torch.tensor(example.target, device="cuda:0")
return {
"examples": examples, "inputs": inputs, "ends": ends,
"prefixes": prefixes, "block_ids": block_ids, "targets": targets,
}
@contextmanager
def scoring_context(batch, causal=False):
# This context stays open during backward as well as forward.
with readout.blocks(None if causal else batch["block_ids"]):
with torch.autocast("cuda", dtype=torch.bfloat16):
yield
def score_batch(bundle, batch):
logits = mm.mm_readout_logits(bundle.model, batch["inputs"], batch["ends"])
ks = [len(example.labels) for example in batch["examples"]]
return common.slot_view(logits, bundle.slot_ids, ks)
@torch.no_grad()
def predict(bundle, rows, seed=None, causal=False):
batch = prepare_batch(bundle, rows, seed=seed)
with scoring_context(batch, causal=causal):
logits, mask = score_batch(bundle, batch)
probabilities = logits.softmax(dim=-1).cpu().tolist()
return [
{label: probabilities[index][position] for position, label in enumerate(example.labels)}
for index, example in enumerate(batch["examples"])
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142"""Candidate routing, validation calibration and benchmark scoring."""
import contextlibimport hashlibimport ioimport jsonimport mathfrom pathlib import Pathimport re
from vendor.metrics.bleu.bleu import Bleufrom vendor.metrics.cider.cider import Ciderfrom vendor.metrics.rouge.rouge import Rouge
ROOT = Path(__file__).resolve().parentDATASETS = ('levir', 'whu', 'dubai')BETAS = [round(step * .02, 2) for step in range(11)]
def read(path): with Path(path).open(encoding='utf-8') as handle: return json.load(handle)
def write(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix('.tmp') temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n', encoding='utf-8') temporary.replace(path)
def read_rows(path): with Path(path).open(encoding='utf-8') as handle: return [json.loads(line) for line in handle if line.strip()]
def digest(path): fingerprint = hashlib.sha256() with Path(path).open('rb') as handle: while chunk := handle.read(1024 * 1024): fingerprint.update(chunk) return fingerprint.hexdigest()
def corpus(dataset, split): return read(ROOT / 'data' / dataset / f'{split}.json')
def profile(dataset): return read(ROOT / 'data' / dataset / 'config.json')
def unchanged(dataset, text, templates): if dataset != 'dubai': return text in templates normalized = ' '.join(re.findall(r'[a-z0-9]+', text.lower())) marker = re.search(r'\b(?:no changes?(?:\s|$)|no changed? to mention|no difference|unchanged|nothing(?: has)? changed|(?:remain(?:s|ed)?|appears?|is|was) the same|the same$)\b', normalized) event = re.search(r'\b(?:built|builds?|construct(?:ed|s|ing)?|new|add(?:ed|s|ing)?|creat(?:ed|es|ing)|realiz(?:ed|es)|edifi(?:ed|es)|demolish(?:ed|es)?|remov(?:ed|es|ing)|urbaniz(?:ed|es|ation)|extend(?:ed|s)?|enlarg(?:ed|es)|expand(?:ed|s|ing)?|increas(?:ed|es)|decreas(?:ed|es)|disappear(?:ed|s|ing)?|different|bigger|smaller)\b', normalized) return normalized in templates or (bool(marker) and not event)
def next_stage(dataset, captions, anchor, templates): if not unchanged(dataset, captions[anchor], templates): return anchor, True if dataset == 'dubai': anchor = next(index for index, text in enumerate(captions) if unchanged(dataset, text, templates)) return anchor, False
def decision(dataset, row, beta, templates): captions = row['captions'] anchor = max(row['stage1'], key=lambda item: item[1])[0] locked, routed = next_stage(dataset, captions, anchor, templates) ranked = row.get('stage2', []) if not routed or not ranked: return locked return max(ranked, key=lambda item: math.log(max(item[1], 1e-30)) - beta * len(captions[item[0]].split()))[0]
def metrics(dataset, references, captions, full=False): vocab = read(ROOT / 'data' / dataset / 'vocab.json') if dataset == 'levir' else None
def encode(text): return ' '.join(str(vocab.get(word, 1)) for word in text.split()) if vocab is not None else text
refs = [[encode(' '.join(tokens)) for tokens in row['references']] for row in references] hyps = [[encode(text)] for text in captions] with contextlib.redirect_stdout(io.StringIO()): bleu, _ = Bleu(4).compute_score(refs, hyps) cider, _ = Cider().compute_score(refs, hyps) values = {f'BLEU{index}': float(value * 100) for index, value in enumerate(bleu, 1)} values['CIDEr'] = float(cider * 100) if full: import os import shutil import tempfile from vendor.metrics.meteor import meteor
if shutil.which('java') is None: raise RuntimeError('METEOR 1.5 requires Java on PATH.') source = Path(meteor.__file__).parent directory = Path(os.environ.get('METEOR_TEMP', tempfile.gettempdir())) / 'ctr-meteor-1.5' if not str(directory).isascii(): raise RuntimeError('Set METEOR_TEMP to a writable ASCII-only directory.') for path in ('meteor-1.5.jar', 'data/paraphrase-en.gz'): target = directory / path target.parent.mkdir(parents=True, exist_ok=True) if not target.is_file() or target.stat().st_size != (source / path).stat().st_size: shutil.copyfile(source / path, target) original = meteor.__file__ try: meteor.__file__ = str(directory / 'meteor.py') values['METEOR'] = float(meteor.Meteor().compute_score(refs, hyps)[0] * 100) finally: meteor.__file__ = original values['ROUGE_L'] = float(Rouge().compute_score(refs, hyps)[0] * 100) values['S_m_star'] = sum(values[key] for key in ('BLEU4', 'METEOR', 'ROUGE_L', 'CIDEr')) / 4 return values
def evaluate(dataset, split, rows, beta, full=False, stage1_only=False): references = corpus(dataset, split) if [row['name'] for row in references] != [row['name'] for row in rows]: raise ValueError(f'{dataset}/{split}: candidate names do not match the benchmark ordering') templates = profile(dataset)['templates'] if stage1_only: selected = [max(row['stage1'], key=lambda item: item[1])[0] for row in rows] else: selected = [decision(dataset, row, beta, templates) for row in rows] outputs = [row['captions'][index] for row, index in zip(rows, selected, strict=True)] return metrics(dataset, references, outputs, full), outputs
def select_beta(dataset, rows): curve = [{'beta': beta, 'metrics': evaluate(dataset, 'val', rows, beta)[0]} for beta in BETAS]
def compare(entry): values = entry['metrics'] return values['CIDEr'] + 2 * values['BLEU4'], values['CIDEr'], values['BLEU4'], -entry['beta']
return max(curve, key=compare), curve1[{"name": "test_000033.png", "en": "False Positive Blocked", "zh": "误报拦截", "media": ["images/test_000033_A.png", "images/test_000033_B.png"]}, {"name": "test_001549.png", "en": "Same-State Reranking", "zh": "同状态精排", "media": ["images/test_001549_A.png", "images/test_001549_B.png"]}, {"name": "test_001324.png", "en": "Length Calibration (β)", "zh": "长度惩罚权衡", "media": ["images/test_001324_A.png", "images/test_001324_B.png"]}, {"name": "test_001095.png", "en": "Boundary / Failure Case", "zh": "边界与失败案例", "media": ["images/test_001095_A.png", "images/test_001095_B.png"]}]12345678910111213141516171819gradio==6.33.0spaces==0.53.0torch==2.8.0torchvision==0.23.0transformers==5.19.0accelerate==1.15.0bitsandbytes==0.50.2peft==0.21.2safetensors==0.8.0flash-linear-attention==0.5.2triton==3.4.0openai-clip==1.0.1einops==0.8.1Pillow==11.0.0six==1.17.0numpy==1.26.4pydantic==2.14.1PyYAML==6.0.3Jinja2==3.1.612345# Third-party components
- `rscama/`: [RSCaMa](https://github.com/Chen-Yang-Liu/RSCaMa), Apache-2.0; see `rscama/NOTICE.md`.- `OneJev/`: inference and slot-training utilities from [OneJev](https://github.com/OmniJev/OneJev) at `81ce62f1597c91e46767d4d02d6ac2e18534fe94`, with the Elephant serving adaptations used in the recorded experiments. `modeling_qwen3_5.py.reference` is the patched Qwen3.5 model implementation from Transformers and retains its original Apache-2.0 notice.- `metrics/`: COCO caption evaluation implementations, with upstream licenses in the source tree. METEOR 1.5 binaries and data retain their upstream terms.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨# This file was automatically generated from src/transformers/models/qwen3_5/modular_qwen3_5.py.# Do NOT edit this file manually as any edits will be overwritten by the generation of# the file from the modular. If any change should be done, please apply the change to the# modular_qwen3_5.py file directly. One of our CI enforces this.# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨# Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import itertoolsfrom collections.abc import Callablefrom dataclasses import dataclass
import torchimport torch.nn.functional as Ffrom torch import nn
from ... import initialization as initfrom ...activations import ACT2FNfrom ...cache_utils import Cache, DynamicCachefrom ...generation import GenerationMixinfrom ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub_with_fallback, use_kernelized_funcfrom ...integrations.accelerate import force_accelerate_hooksfrom ...masking_utils import create_causal_mask, create_recurrent_attention_maskfrom ...modeling_flash_attention_utils import FlashAttentionKwargsfrom ...modeling_layers import ( GenericForSequenceClassification, GenericForTokenClassification, GradientCheckpointingLayer,)from ...modeling_outputs import ( BaseModelOutputWithPast, BaseModelOutputWithPooling, CausalLMOutputWithPast, SequenceClassifierOutputWithPast,)from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_updatefrom ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModelfrom ...processing_utils import Unpackfrom ...utils import ( TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_exporting, torch_compilable_check,)from ...utils.generic import ( accepts_precomputed_kwargs, get_max_seqlen, is_flash_attention_requested, maybe_autocast, merge_with_config_defaults,)from ...utils.output_capturing import capture_outputsfrom ...vision_utils import ( get_vision_attention_seqlens, get_vision_interpolation_indices_and_weights, get_vision_position_ids,)from ..auto import AutoModelfrom .configuration_qwen3_5 import Qwen3_5Config, Qwen3_5TextConfig, Qwen3_5VisionConfig
class Qwen3_5VisionRotaryEmbedding(nn.Module): """ Simple axial 2D rope with same freqs used for H and W grids. The freqs are pre-computed using `head-dim//4` which is later used to concat H and W positions. The final angles rotate over the whole head dim, no partial rotation involved. """
def __init__(self, config: Qwen3_5VisionConfig): super().__init__() self.config = config
self.rope_type = self.config.rope_parameters["rope_type"] rope_init_fn: Callable = self.compute_axial_rope_parameters if self.rope_type != "axial": raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") inv_freq, self.attention_scaling = rope_init_fn(self.config)
self.inv_freq = nn.Buffer(inv_freq, persistent=False) self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False)
@staticmethod def compute_axial_rope_parameters( config: Qwen3_5VisionConfig, device=None, **kwargs ) -> tuple[torch.Tensor, float]: """ Computes the inverse frequencies according to the original RoPE implementation Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ base = config.rope_parameters["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads spatial_dim = dim // 2
attention_factor = 1.0 # Unused in this type of RoPE inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) return inv_freq.to(device), attention_factor
@torch.no_grad() def forward(self, x, position_ids): # position_ids: (2, N) — row 0 = h coords, row 1 = w coords position_ids_expanded = position_ids[..., None].float() device_type = x.device.type if isinstance(x.device.type, str) else "cpu" with maybe_autocast(device_type=device_type, enabled=False): freqs = position_ids_expanded * self.inv_freq.float() cos = freqs.cos() * self.attention_scaling sin = freqs.sin() * self.attention_scaling
cos = self.recomposition_frequencies(cos) sin = self.recomposition_frequencies(sin) return cos, sin
def recomposition_frequencies(self, freq): """ Recompose the frequencies into the final spatial layout used per each grid. """ freq_h, freq_w = freq[:, 0], freq[:, 1] freq_hw = torch.cat([freq_h, freq_w], dim=-1) return torch.cat([freq_hw, freq_hw], dim=-1)
class Qwen3_5TextRotaryEmbedding(nn.Module): def __init__(self, config: Qwen3_5TextConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.config.rope_parameters["rope_type"] rope_init_fn: Callable = self.compute_default_rope_parameters if self.rope_type != "default": rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] inv_freq, self.attention_scaling = rope_init_fn(self.config)
self.inv_freq = nn.Buffer(inv_freq, persistent=False) self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) self.mrope_section = config.rope_parameters.get("mrope_section", [11, 11, 10])
@staticmethod def compute_default_rope_parameters( config: Qwen3_5TextConfig, device=None, **kwargs ) -> tuple[torch.Tensor, float]: """ Computes the inverse frequencies according to the original RoPE implementation Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ base = config.rope_parameters["rope_theta"] partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0) head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads dim = int(head_dim * partial_rotary_factor)
attention_factor = 1.0 # Unused in this type of RoPE # Compute the inverse frequencies inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor
@torch.no_grad() @dynamic_rope_update def forward(self, x, position_ids): # In contrast to other models, Qwen3_5Text has different position ids for the grids # So position_ids is broadcast to (3, bs, positions) and freqs has shape (3, bs, positions, dim // 2) position_ids = position_ids.expand(3, -1, -1) freqs = position_ids[..., None].float() * self.inv_freq.to(device=x.device, dtype=torch.float) cos = freqs.cos() * self.attention_scaling sin = freqs.sin() * self.attention_scaling
sin = self.recomposition_frequencies(sin) cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def recomposition_frequencies(self, freq): """ Recompose the frequencies into the final spatial layout used per each grid. """ freqs_thw = freq[0] # just overwrite the first dimension T for dim, offset in enumerate((1, 2), start=1): # H, W length = self.mrope_section[dim] * 3 idx = slice(offset, length, 3) freqs_thw[..., idx] = freq[dim, ..., idx] return torch.cat((freqs_thw, freqs_thw), dim=-1)
# NOTE: the FLA package does not re-cast to `input_dtype` in its implementation, maybe we should do the same@use_kernel_forward_from_hub("RMSNormGated")class Qwen3_5RMSNormGated(nn.Module): def __init__(self, hidden_size: int, eps: float = 1e-6, **kwargs) -> None: super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps self.activation = "silu"
def forward(self, hidden_states: torch.Tensor, gate: torch.Tensor) -> torch.Tensor: input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) # Norm before gate hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) hidden_states = self.weight * hidden_states.to(input_dtype) hidden_states = hidden_states * ACT2FN[self.activation](gate.to(torch.float32))
return hidden_states.to(input_dtype)
def apply_mask_to_padding_states(hidden_states, attention_mask): """ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66 """ # NOTE: attention mask is a 2D boolean tensor if attention_mask is not None: dtype = hidden_states.dtype hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
return hidden_states
@use_kernel_func_from_hub_with_fallback("causal_conv1d_update", "causal_conv1d")def causal_conv1d_update( hidden_states: torch.Tensor, conv_state: torch.Tensor, weight: nn.Parameter, bias: nn.Parameter | None = None, activation: str | None = None,): _, hidden_size, seq_len = hidden_states.shape state_len = conv_state.shape[-1]
hidden_states_new = torch.cat([conv_state, hidden_states], dim=-1).to(weight.dtype) conv_state.copy_(hidden_states_new[:, :, -state_len:]) out = F.conv1d(hidden_states_new, weight.unsqueeze(1), bias, padding=0, groups=hidden_size) out = out[:, :, -seq_len:] if activation is not None: out = ACT2FN[activation](out) return out.to(hidden_states.dtype)
@use_kernel_func_from_hub_with_fallback("causal_conv1d_fn", "causal_conv1d")def causal_conv1d_fn( hidden_states: torch.Tensor, weight: nn.Parameter, bias: nn.Parameter | None = None, activation: str | None = None, **kwargs,): _, hidden_size, seq_len = hidden_states.shape padding = weight.shape[-1] - 1
out = F.conv1d( hidden_states.to(weight.dtype), weight=weight.unsqueeze(1), bias=bias, padding=padding, groups=hidden_size, )[:, :, :seq_len] if activation is not None: out = ACT2FN[activation](out) return out.to(hidden_states.dtype)
# NOTE: the FLA package computes `x / torch.sqrt((x * x).sum(dim=dim, keepdim=True) + eps)` instead, so if we align# with the GatedRMSNorm, maybe we can make that change as well.def l2norm(x: torch.FloatTensor, dim: int = -1, eps: float = 1e-6): """This function is intended to align with the l2norm implementation in the FLA library.""" inv_norm = torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps) return x * inv_norm
@use_kernel_func_from_hub_with_fallback("chunk_gated_delta_rule", "fla")def torch_chunk_gated_delta_rule( query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, g: torch.Tensor, beta: torch.Tensor, chunk_size: int = 64, initial_state: torch.Tensor | None = None, output_final_state: bool = False, use_qk_l2norm_in_kernel: bool = False, **kwargs,) -> tuple[torch.Tensor, torch.Tensor | None]: """Computes the gated delta rule, by chunking along the sequence dimension. Args: query: Query tensor of shape [batch_size, sequence_length, num_k_heads, k_head_dim] key: Key tensor of shape [batch_size, sequence_length, num_k_heads, k_head_dim] value: Value tensor of shape [batch_size, sequence_length, num_v_heads, v_head_dim]. num_v_heads can be equal to num_k_heads, same for v_head_dim and k_head_dim. g: Decay (in log space) tensor of shape [batch_size, sequence_length, num_v_heads]: the recurrent state is multiplied by exp(g) at each step, so entries must be <= 0. beta: Beta tensor of shape [batch_size, sequence_length, num_v_heads] chunk_size: Size of the chunks along the sequence dimension. initial_state: The recurrent state, an optional tensor of shape [batch_size, num_v_heads, k_head_dim, v_head_dim] output_final_state: Whether to output the new recurrent state along with the output. use_qk_l2norm_in_kernel: If this flag is set to True, query and key vectors are L2-normalized. Returns: - The output tensor of shape [batch_size, sequence_length, num_v_heads, v_head_dim] - Either None or the new recurrent state tensor of shape [batch_size, num_v_heads, k_head_dim, v_head_dim] """ initial_dtype = query.dtype batch_size, sequence_length, _, k_head_dim = key.shape num_v_heads, v_head_dim = value.shape[-2:] recurrent_state_shape = (batch_size, num_v_heads, k_head_dim, v_head_dim) padded_output_shape = (batch_size, num_v_heads, -1, v_head_dim) # -1 is the padded sequence length decay = g # rename for clarity: argument name must stay "g" to match flash_linear_attention's API
# Make sure all tensors are fp32 and reshape them to [batch_size, num_*_heads, seqlen, ...] query, key, value, beta, decay = [ x.transpose(1, 2).to(torch.float32, memory_format=torch.contiguous_format) for x in (query, key, value, beta, decay) ] # If enabled, normalize query and key vectors (in fp32 to match the FLA library) if use_qk_l2norm_in_kernel: query = l2norm(query, dim=-1, eps=1e-6) key = l2norm(key, dim=-1, eps=1e-6) # And always normalize queries by the head dimension scaling = query.shape[-1] ** -0.5 query = query * scaling
# Pad sequence length to be a multiple of chunk_size. Padding is described as (left_pad, right_pad) for each dim. pad_size = (chunk_size - sequence_length % chunk_size) % chunk_size query, key, value = (F.pad(x, (0, 0, 0, pad_size)) for x in (query, key, value)) beta, decay = (F.pad(x, (0, pad_size)) for x in (beta, decay))
total_sequence_length = sequence_length + pad_size num_chunks = total_sequence_length // chunk_size
# Apply beta to K and V, which is the "learning rate" of the recurrent state for a given token, ie. how much the new # state influence the old state. Beta is often normalized to (0, 1) where 0 = no update; 1 = overwrite old state. v_beta = value * beta.unsqueeze(-1) k_beta = key * beta.unsqueeze(-1)
# Reshape all tensors to chunk the sequence dimension (adds a new dimension of size chunk_size) query, key, k_beta, v_beta = [ x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) for x in (query, key, k_beta, v_beta) ] decay = decay.reshape(decay.shape[0], decay.shape[1], -1, chunk_size)
# Create a chunk-sized strictly upper triangular mask, ie. the mask of what a causal chunk may not attend to strictly_upper_mask = torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device).triu(1)
# Cumulative decay within each chunk (dim 3 is the position inside the chunk). Since decay is in log space, # cum_decay[..., t] is the log of a product of decays between the start of the chunk and position t cum_decay = decay.cumsum(dim=3)
# First phase: compute intra-chunk quantities. # The pairwise decays: pairwise_decay[..., i, j] = exp(cum_decay_i - cum_decay_j) is the decay accumulated between # positions j and i of a chunk. Positive values are masked to -inf before exp to avoid overflow pairwise_decay = cum_decay.unsqueeze(4) - cum_decay.unsqueeze(3) pairwise_decay = pairwise_decay.masked_fill(strictly_upper_mask, float("-inf")) pairwise_decay = pairwise_decay.exp() # with the exp, we exit log space, so we can apply this decay to the states
# Compute auxiliary tensors: the Upper Triangular (ut) transform system and the intra-chunk attn (QK dot product) ut_system = (k_beta @ key.transpose(-1, -2)) * pairwise_decay intra_chunk_attn = (query @ key.transpose(-1, -2)) * pairwise_decay decayed_k_beta = k_beta * cum_decay.exp().unsqueeze(-1)
# Gated delta attention uses a UT transform to condense several delta rule updates into a few matmuls. After the UT # system is solved, we can then compute the new_values (called "u" in the DeltaNet paper) and the decayed keys # reading the old state (k_cumdecay). In the update, the part of new_values that the old state already predicts is # subtracted out, so that only the correction is written to the recurrent state: this is the delta rule.
# Not all export targets support the fast triangular solver, so we build the inverse by forward substitution then if not is_torchdynamo_exporting(): new_values = torch.linalg.solve_triangular(ut_system, v_beta, upper=False, unitriangular=True) k_cumdecay = torch.linalg.solve_triangular(ut_system, decayed_k_beta, upper=False, unitriangular=True) else: ut_system = -ut_system.tril(-1) # ut_system is masked to only keep the strictly lower triangle for i in range(1, chunk_size): row = ut_system[..., i, :i].clone() sub = ut_system[..., :i, :i].clone() ut_system[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2) ut_system = ut_system + torch.eye(chunk_size, dtype=ut_system.dtype, device=ut_system.device) new_values, k_cumdecay = ut_system @ v_beta, ut_system @ decayed_k_beta
if initial_state is None: last_recurrent_state = torch.zeros(recurrent_state_shape, dtype=new_values.dtype, device=new_values.device) else: last_recurrent_state = initial_state.to(new_values) core_attn_out = torch.zeros_like(new_values)
# Apply decay once rather than in each chunk query = query * cum_decay.exp().unsqueeze(-1) key = key * (cum_decay[..., -1:] - cum_decay).exp().unsqueeze(-1) chunk_decay = cum_decay[..., -1].exp()[..., None, None]
# Second phase: the sequential scan over chunks for i in range(num_chunks): # Compute attention output for the current chunk: add the read of the previous recurrent state # (inter_chunk_attn) with the within-chunk attention (intra_chunk_attn) v_new = new_values[:, :, i] - k_cumdecay[:, :, i] @ last_recurrent_state inter_chunk_attn = query[:, :, i] @ last_recurrent_state core_attn_out[:, :, i] = inter_chunk_attn + intra_chunk_attn[:, :, i] @ v_new # Update the recurrent state: new recurrent state (S_t+1) = decayed old state (S_t * (I-βkk^T)) + update (βvk^T) last_recurrent_state = last_recurrent_state * chunk_decay[:, :, i] + key[:, :, i].transpose(-1, -2) @ v_new
# Discard the final state if not requested last_recurrent_state = None if not output_final_state else last_recurrent_state # Reshape the output to the orignal shape: flatten the chunk dimension, then drop padding core_attn_out = core_attn_out.reshape(padded_output_shape) core_attn_out = core_attn_out[:, :, :sequence_length] # Convert back to the original shape [batch_size, sequence_length, num_v_heads, v_head_dim] and dtype core_attn_out = core_attn_out.transpose(1, 2).to(initial_dtype, memory_format=torch.contiguous_format) return core_attn_out, last_recurrent_state
@use_kernel_func_from_hub_with_fallback("fused_recurrent_gated_delta_rule", "fla")def torch_recurrent_gated_delta_rule( query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, g: torch.Tensor, beta: torch.Tensor, initial_state: torch.Tensor | None = None, output_final_state: bool = False, use_qk_l2norm_in_kernel: bool = False, **kwargs,) -> tuple[torch.Tensor, torch.Tensor | None]: """Computes linear attention using the gated delta rule, by iterating over each token in the sequence dimension. Same args and return value as torch_chunk_gated_delta_rule, except for `chunk_size` because the sequence dim is not chunked.""" initial_dtype = query.dtype batch_size, sequence_length, _, k_head_dim = key.shape num_v_heads, v_head_dim = value.shape[-2:] decay = g # rename for clarity: argument name must stay "g" to match flash_linear_attention's API
# Make sure all tensors are fp32 and reshape them to [batch_size, num_*_heads, seqlen, ...] query, key, value, beta, decay = [ x.transpose(1, 2).to(torch.float32, memory_format=torch.contiguous_format) for x in (query, key, value, beta, decay) ] # If enabled, normalize query and key vectors (done once in fp32 for better accuracy) if use_qk_l2norm_in_kernel: query = l2norm(query, dim=-1, eps=1e-6) key = l2norm(key, dim=-1, eps=1e-6)
# And always normalize queries by the head dimension query = query / (query.shape[-1] ** 0.5)
# Create the storage for the last recurrent state, which will be updated in place. If a previous state is provided, # it is the starting point, otherwise start with a zeroed buffer. if initial_state is None: recurrent_state_shape = (batch_size, num_v_heads, k_head_dim, v_head_dim) last_recurrent_state = torch.zeros(recurrent_state_shape, dtype=value.dtype, device=value.device) else: last_recurrent_state = initial_state.to(value) core_attn_out = torch.zeros_like(value)
# Loop over each token and update the recurrent state for i in range(sequence_length): q_t, k_t, v_t = query[:, :, i], key[:, :, i], value[:, :, i] # Decay the recurrent state decay_t = decay[:, :, i].exp()[..., None, None] last_recurrent_state = last_recurrent_state * decay_t # Update the recurrent state with the current token beta_t = beta[:, :, i].unsqueeze(-1) kv_mem = (last_recurrent_state * k_t.unsqueeze(-1)).sum(dim=-2) delta = (v_t - kv_mem) * beta_t last_recurrent_state = last_recurrent_state + k_t.unsqueeze(-1) * delta.unsqueeze(-2) # And use it to compute the attention output for the current token core_attn_out[:, :, i] = (last_recurrent_state * q_t.unsqueeze(-1)).sum(dim=-2)
# Discard the final state if not requested last_recurrent_state = None if not output_final_state else last_recurrent_state # Convert back to the original shape [batch_size, sequence_length, num_v_heads, v_head_dim] and dtype core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype) return core_attn_out, last_recurrent_state
@use_kernel_forward_from_hub("Qwen3_5GatedDeltaNet")@use_kernelized_func( [torch_recurrent_gated_delta_rule, torch_chunk_gated_delta_rule, causal_conv1d_fn, causal_conv1d_update])class Qwen3_5GatedDeltaNet(nn.Module): def __init__(self, config: Qwen3_5Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.num_v_heads = config.linear_num_value_heads self.num_k_heads = config.linear_num_key_heads self.head_k_dim = config.linear_key_head_dim self.head_v_dim = config.linear_value_head_dim self.key_dim = self.head_k_dim * self.num_k_heads self.value_dim = self.head_v_dim * self.num_v_heads
self.conv_kernel_size = config.linear_conv_kernel_dim self.layer_idx = layer_idx self.activation = config.hidden_act self.layer_norm_epsilon = config.rms_norm_eps
# QKV self.conv_dim = self.key_dim * 2 + self.value_dim self.conv1d = nn.Conv1d( in_channels=self.conv_dim, out_channels=self.conv_dim, bias=False, kernel_size=self.conv_kernel_size, groups=self.conv_dim, padding=self.conv_kernel_size - 1, )
# time step projection (discretization) # instantiate once and copy inv_dt in init_weights of PretrainedModel self.dt_bias = nn.Parameter(torch.ones(self.num_v_heads))
# Lower bound kept away from 0 so log(A) never becomes -inf A = torch.empty(self.num_v_heads).uniform_(0.01, 16) self.A_log = nn.Parameter(torch.log(A))
self.norm = Qwen3_5RMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon) self.out_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
self.layer_type = config.layer_types[layer_idx]
self.in_proj_qkv = nn.Linear(self.hidden_size, self.key_dim * 2 + self.value_dim, bias=False) self.in_proj_z = nn.Linear(self.hidden_size, self.value_dim, bias=False) self.in_proj_b = nn.Linear(self.hidden_size, self.num_v_heads, bias=False) self.in_proj_a = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
@force_accelerate_hooks("conv1d") def forward( self, hidden_states: torch.Tensor, cache_params: Cache | None = None, attention_mask: torch.Tensor | None = None, **kwargs: Unpack[TransformersKwargs], ): hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
# Set up dimensions for reshapes later batch_size, seq_len, _ = hidden_states.shape use_precomputed_states = cache_params is not None and cache_params.has_previous_state( self.layer_idx, state_idx=0 )
mixed_qkv = self.in_proj_qkv(hidden_states) mixed_qkv = mixed_qkv.transpose(1, 2)
z = self.in_proj_z(hidden_states) z = z.reshape(batch_size, seq_len, -1, self.head_v_dim)
b = self.in_proj_b(hidden_states) a = self.in_proj_a(hidden_states)
if use_precomputed_states and seq_len == 1 and not cache_params.layers[self.layer_idx].record_past: conv_state = cache_params.layers[self.layer_idx].conv_states[0] # Single-token cached decode: the fused per-step kernel updates the conv state in-place. mixed_qkv = causal_conv1d_update( mixed_qkv, conv_state, self.conv1d.weight.squeeze(1), self.conv1d.bias, self.activation, ) else: if cache_params is not None: mixed_qkv = cache_params.update_conv_state( mixed_qkv, self.layer_idx, conv_kernel_size=self.conv_kernel_size )
mixed_qkv = causal_conv1d_fn( mixed_qkv, self.conv1d.weight.squeeze(1), self.conv1d.bias, activation=self.activation, **kwargs, )
# Drop the additional previous states if cache_params is not None: mixed_qkv = mixed_qkv[:, :, -seq_len:]
mixed_qkv = mixed_qkv.transpose(1, 2) query, key, value = torch.split( mixed_qkv, [ self.key_dim, self.key_dim, self.value_dim, ], dim=-1, )
query = query.reshape(batch_size, seq_len, -1, self.head_k_dim) key = key.reshape(batch_size, seq_len, -1, self.head_k_dim) value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
beta = b.sigmoid() # If the model is loaded in fp16, without the .float() here, A might be -inf g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias) if self.num_v_heads // self.num_k_heads > 1: query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2) key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
recurrent_state = cache_params.layers[self.layer_idx].recurrent_states[0] if use_precomputed_states else None if use_precomputed_states and seq_len == 1: core_attn_out, last_recurrent_state = torch_recurrent_gated_delta_rule( query, key, value, g=g, beta=beta, initial_state=recurrent_state, output_final_state=cache_params is not None, use_qk_l2norm_in_kernel=True, cu_seqlens=kwargs.pop("cu_seq_lens_q", None), **kwargs, ) else: core_attn_out, last_recurrent_state = torch_chunk_gated_delta_rule( query, key, value, g=g, beta=beta, initial_state=recurrent_state, output_final_state=cache_params is not None, use_qk_l2norm_in_kernel=True, cu_seqlens=kwargs.pop("cu_seq_lens_q", None), **kwargs, )
# Update cache if cache_params is not None: cache_params.update_recurrent_state(last_recurrent_state, self.layer_idx)
# reshape input data into 2D tensor core_attn_out = core_attn_out.reshape(-1, self.head_v_dim) z = z.reshape(-1, self.head_v_dim) core_attn_out = self.norm(core_attn_out, z) core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
output = self.out_proj(core_attn_out) return output
def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
# Adapted from transformers.models.glm.modular_glm.apply_rotary_pos_embdef apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors.
Removes the interleaving of cos and sin from GLM
Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim)
# Keep half or full tensor for later concatenation rotary_dim = cos.shape[-1] q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:] k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
# Apply rotary embeddings on the first half or full tensor q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin) k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
# Concatenate back to full shape q_embed = torch.cat([q_embed, q_pass], dim=-1) k_embed = torch.cat([k_embed, k_pass], dim=-1) return q_embed, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor | None, scaling: float, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs],): key_states = repeat_kv(key, module.num_key_value_groups) value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling if attention_mask is not None: attn_weights = attn_weights + attention_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
class Qwen3_5Attention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Qwen3_5Config, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.is_causal = True self.q_proj = nn.Linear( config.hidden_size, config.num_attention_heads * self.head_dim * 2, bias=config.attention_bias ) self.k_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.v_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.o_proj = nn.Linear( config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias ) self.q_norm = Qwen3_5RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim! self.k_norm = Qwen3_5RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None, past_key_values: Cache | None = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, torch.Tensor | None]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim)
query_states, gate = torch.chunk( self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1 ) gate = gate.reshape(*input_shape, -1)
query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2) key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2) value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None: key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward )
attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, )
attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = attn_output * torch.sigmoid(gate)
attn_output = self.o_proj(attn_output) return attn_output, attn_weights
class Qwen3_5MLP(nn.Module): def __init__(self, config: Qwen3_5Config, intermediate_size: int): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x): down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) return down_proj
@use_kernel_forward_from_hub("RMSNormZeroCentered")class Qwen3_5RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.zeros(dim))
def _norm(self, x): return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x): output = self._norm(x.float()) # Llama does x.to(float16) * w whilst Qwen3_5 is (x * w).to(float16) # See https://github.com/huggingface/transformers/pull/29402 output = output * (1.0 + self.weight.float()) return output.type_as(x)
def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.eps}"
class Qwen3_5DecoderLayer(GradientCheckpointingLayer): def __init__(self, config: Qwen3_5TextConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.block_type = config.layer_types[layer_idx] if self.block_type == "linear_attention": self.linear_attn = Qwen3_5GatedDeltaNet(config, layer_idx) elif self.block_type == "full_attention": self.self_attn = Qwen3_5Attention(config, layer_idx) self.mlp = Qwen3_5MLP(config, config.intermediate_size) self.input_layernorm = Qwen3_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = Qwen3_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, **kwargs: Unpack[TransformersKwargs], ) -> torch.FloatTensor: residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Token Mixer if self.block_type == "linear_attention": hidden_states = self.linear_attn( hidden_states=hidden_states, cache_params=past_key_values, attention_mask=attention_mask, **kwargs, ) elif self.block_type == "full_attention": # Self Attention hidden_states, _ = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, position_embeddings=position_embeddings, **kwargs, )
hidden_states = residual + hidden_states
# Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states
return hidden_states
class Qwen3_5PreTrainedModel(PreTrainedModel): config: Qwen3_5Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Qwen3_5DecoderLayer", "Qwen3_5VisionBlock"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _keys_to_ignore_on_load_unexpected = [r"^mtp.*"] _can_record_outputs = { "hidden_states": Qwen3_5DecoderLayer, "attentions": Qwen3_5Attention, } _is_stateful = True _can_compile_fullgraph = True
@torch.no_grad() def _init_weights(self, module): super()._init_weights(module) if isinstance(module, Qwen3_5GatedDeltaNet): init.ones_(module.dt_bias) # Lower bound kept away from 0 so log(A) never becomes -inf init.copy_( module.A_log, torch.empty(module.num_v_heads, device=module.A_log.device).uniform_(0.01, 16).log_(), ) # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight) elif isinstance(module, Qwen3_5RMSNorm): init.zeros_(module.weight)
class Qwen3_5VisionMLP(nn.Module): def __init__(self, config): super().__init__() self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.linear_fc1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=True) self.linear_fc2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=True) self.act_fn = ACT2FN[config.hidden_act]
def forward(self, hidden_state): return self.linear_fc2(self.act_fn(self.linear_fc1(hidden_state)))
class Qwen3_5VisionPatchEmbed(nn.Module): def __init__(self, config) -> None: super().__init__() self.patch_size = config.patch_size self.temporal_patch_size = config.temporal_patch_size self.in_channels = config.in_channels self.embed_dim = config.hidden_size
kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size] self.proj = nn.Conv3d(self.in_channels, self.embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=True)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: target_dtype = self.proj.weight.dtype hidden_states = hidden_states.view( -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size ) hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim) return hidden_states
class Qwen3_5VisionPatchMerger(nn.Module): def __init__(self, config: Qwen3_5VisionConfig, use_postshuffle_norm=False) -> None: super().__init__() self.hidden_size = config.hidden_size * (config.spatial_merge_size**2) self.use_postshuffle_norm = use_postshuffle_norm self.norm = nn.LayerNorm(self.hidden_size if use_postshuffle_norm else config.hidden_size, eps=1e-6) self.linear_fc1 = nn.Linear(self.hidden_size, self.hidden_size) self.act_fn = nn.GELU() self.linear_fc2 = nn.Linear(self.hidden_size, config.out_hidden_size)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.norm(x.view(-1, self.hidden_size) if self.use_postshuffle_norm else x).view(-1, self.hidden_size) x = self.linear_fc2(self.act_fn(self.linear_fc1(x))) return x
def apply_rotary_pos_emb_vision( q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: orig_q_dtype = q.dtype orig_k_dtype = k.dtype q, k = q.float(), k.float() cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float() q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) q_embed = q_embed.to(orig_q_dtype) k_embed = k_embed.to(orig_k_dtype) return q_embed, k_embed
class Qwen3_5VisionAttention(nn.Module): def __init__(self, config: Qwen3_5VisionConfig) -> None: super().__init__() self.dim = config.hidden_size self.num_heads = config.num_heads self.head_dim = self.dim // self.num_heads self.num_key_value_groups = 1 # needed for eager attention self.qkv = nn.Linear(self.dim, self.dim * 3, bias=True) self.proj = nn.Linear(self.dim, self.dim) self.scaling = self.head_dim**-0.5 self.config = config self.attention_dropout = 0.0 self.is_causal = False
def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, max_seqlen: int | None = None, **kwargs, ) -> torch.Tensor: seq_length = hidden_states.shape[0] query_states, key_states, value_states = ( self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0) ) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)
query_states = query_states.transpose(0, 1).unsqueeze(0) key_states = key_states.transpose(0, 1).unsqueeze(0) value_states = value_states.transpose(0, 1).unsqueeze(0)
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward )
if is_flash_attention_requested(self.config): # Flash Attention: Use cu_seqlens for variable length attention max_seqlen = get_max_seqlen(cu_seqlens, self.config, kwargs={"max_seqlen": max_seqlen}) attn_output, _ = attention_interface( self, query_states, key_states, value_states, attention_mask=None, scaling=self.scaling, dropout=0.0 if not self.training else self.attention_dropout, cu_seq_lens_q=cu_seqlens, cu_seq_lens_k=cu_seqlens, max_length_q=max_seqlen, max_length_k=max_seqlen, is_causal=False, **kwargs, ) else: # Other implementations: Process each chunk separately lengths = cu_seqlens[1:] - cu_seqlens[:-1] splits = [ torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states) ]
attn_outputs = [ attention_interface( self, q, k, v, attention_mask=None, scaling=self.scaling, dropout=0.0 if not self.training else self.attention_dropout, is_causal=False, **kwargs, )[0] for q, k, v in zip(*splits) ] attn_output = torch.cat(attn_outputs, dim=1)
attn_output = attn_output.reshape(seq_length, -1).contiguous() attn_output = self.proj(attn_output) return attn_output
class Qwen3_5VisionBlock(GradientCheckpointingLayer): def __init__(self, config, attn_implementation: str = "sdpa") -> None: super().__init__() self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6) self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6) self.attn = Qwen3_5VisionAttention(config=config) self.mlp = Qwen3_5VisionMLP(config=config)
@auto_docstring def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs, ) -> torch.Tensor: r""" cu_seqlens (`torch.Tensor`): Cumulative sequence lengths used for packed variable-length attention in Flash Attention kernels. """ hidden_states = hidden_states + self.attn( self.norm1(hidden_states), cu_seqlens=cu_seqlens, position_embeddings=position_embeddings, **kwargs, ) hidden_states = hidden_states + self.mlp(self.norm2(hidden_states)) return hidden_states
class Qwen3_5VisionModel(Qwen3_5PreTrainedModel): config: Qwen3_5VisionConfig input_modalities = ("image", "video") _can_record_outputs = { "hidden_states": Qwen3_5VisionBlock, "attentions": Qwen3_5VisionAttention, } _no_split_modules = ["Qwen3_5VisionBlock"]
def __init__(self, config, *inputs, **kwargs) -> None: super().__init__(config, *inputs, **kwargs) self.spatial_merge_size = config.spatial_merge_size self.patch_size = config.patch_size self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size
self.patch_embed = Qwen3_5VisionPatchEmbed( config=config, )
self.pos_embed = nn.Embedding(config.num_position_embeddings, config.hidden_size) # How the (square) learned position grid is resampled to each image's grid. self.num_grid_per_side = int(config.num_position_embeddings**0.5) self.interpolation_align_corners = True self.interpolation_mode = "bilinear"
self.rotary_pos_emb = Qwen3_5VisionRotaryEmbedding(config)
self.blocks = nn.ModuleList([Qwen3_5VisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen3_5VisionPatchMerger( config=config, use_postshuffle_norm=False, )
self.gradient_checkpointing = False
self.post_init()
@merge_with_config_defaults @capture_outputs def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) -> torch.Tensor: """ Args: hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`): The final hidden states of the model. grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`): The temporal, height and width of feature shape of each image in LLM.
Returns: `torch.Tensor`: hidden_states. """ interp_indices, interp_weights = get_vision_interpolation_indices_and_weights( grid_thw, num_grid_per_side=self.num_grid_per_side, mode=self.interpolation_mode, align_corners=self.interpolation_align_corners, spatial_merge_size=self.config.spatial_merge_size, kwargs=kwargs, ) position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, kwargs=kwargs) cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs)
hidden_states = self.patch_embed(hidden_states) pos_embeds = (self.pos_embed(interp_indices) * interp_weights[:, :, None]).sum(1) hidden_states = hidden_states + pos_embeds.to(hidden_states.dtype) position_embeddings = self.rotary_pos_emb(hidden_states, position_ids)
seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len, -1)
for blk in self.blocks: hidden_states = blk( hidden_states, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen, position_embeddings=position_embeddings, **kwargs, )
merged_hidden_states = self.merger(hidden_states)
return BaseModelOutputWithPooling( last_hidden_state=hidden_states, pooler_output=merged_hidden_states, )
@auto_docstring@dataclassclass Qwen3_5ModelOutputWithPast(BaseModelOutputWithPast): r""" rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*): The rope index difference between sequence length and multimodal rope. The attribute is deprecated and will be removed in v5.20, use `model.base_model.rope_deltas` instead. """
rope_deltas: torch.LongTensor | None = None
class Qwen3_5TextModel(Qwen3_5PreTrainedModel): config: Qwen3_5TextConfig
def __init__(self, config: Qwen3_5TextConfig): super().__init__(config) self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id) self.layers = nn.ModuleList( [Qwen3_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = Qwen3_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = Qwen3_5TextRotaryEmbedding(config=config) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init()
@merge_with_config_defaults @capture_outputs @auto_docstring def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPast: if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids)
if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config)
# the hard coded `4` is for text, temporal, height and width. if position_ids is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens position_ids = position_ids.view(1, 1, -1).expand(4, inputs_embeds.shape[0], -1) elif position_ids.ndim == 2: position_ids = position_ids[None, ...].expand(4, position_ids.shape[0], -1)
if position_ids.ndim == 3 and position_ids.shape[0] == 4: text_position_ids = position_ids[0] position_ids = position_ids[1:] else: text_position_ids = None
if not isinstance(causal_mask_mapping := attention_mask, dict): # Prepare mask arguments mask_kwargs = { "config": self.config, "inputs_embeds": inputs_embeds, "attention_mask": attention_mask, "past_key_values": past_key_values, "position_ids": text_position_ids, } # Create the masks causal_mask_mapping = { "full_attention": create_causal_mask(**mask_kwargs), "linear_attention": create_recurrent_attention_mask(**mask_kwargs), }
hidden_states = inputs_embeds position_embeddings = self.rotary_emb(hidden_states, position_ids)
for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]): hidden_states = decoder_layer( hidden_states, position_embeddings=position_embeddings, attention_mask=causal_mask_mapping[self.config.layer_types[i]], position_ids=text_position_ids, past_key_values=past_key_values, use_cache=use_cache, **kwargs, )
hidden_states = self.norm(hidden_states)
return Qwen3_5ModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values, )
@auto_docstringclass Qwen3_5Model(Qwen3_5PreTrainedModel): base_model_prefix = "model" # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False _no_split_modules = ["Qwen3_5DecoderLayer", "Qwen3_5VisionBlock"]
def __init__(self, config): super().__init__(config) self.visual = AutoModel.from_config(config.vision_config) self.language_model = AutoModel.from_config(config.text_config) self.rope_deltas = None # cache rope_deltas here
# Initialize weights and apply final processing self.post_init()
def get_vision_position_ids( self, start_position: int, grid_thw: list[int, int, int] | torch.Tensor, temp_merge_size: int = 1, spatial_merge_size: int = 1, time_interval: float | torch.Tensor = 1.0, device: str | torch.device | None = None, ): """ Compute 3D positional indices for vision tokens derived from a single image or video input.
The positions are generated from the input grid defined by temporal (T), height (H), and width (W) dimensions. Temporal and spatial dimensions can be downscaled according to the merge sizes used in the vision backbone. The resulting positions are offset by `start_position`.
Args: start_position (`int`): Offset added to all computed positional indices. grid_thw (`Sequence[int]` or `torch.Tensor` of shape `(3,)`): The (T, H, W) grid representing the feature layout of the current image or video after patch embedding. temp_merge_size (`int`, *optional*): Factor by which the temporal dimension is reduced in the backbone. The temporal grid size is divided by this value. Defaults to 1. spatial_merge_size (`int`, *optional*): Factor by which the spatial dimensions (H and W) are reduced in the backbone. Both H and W are divided by this value. Defaults to 1. time_interval (`float` or scalar `torch.Tensor`, *optional*, defaults to 1.0): Spacing factor applied before quantizing temporal position indices. device (`str` or `torch.device`, *optional*): Device on which the resulting tensor is allocated. If `None`, uses the current default device.
Returns: torch.LongTensor of shape (3, sequence_length): Positional indices for temporal, height, and width dimensions, flattened into sequence form and offset by `start_position`. """ llm_grid_t, llm_grid_h, llm_grid_w = ( grid_thw[0].item() // temp_merge_size, grid_thw[1].item() // spatial_merge_size, grid_thw[2].item() // spatial_merge_size, )
position_temporal = (torch.arange(llm_grid_t, device=device) * time_interval).long() position_height = torch.arange(llm_grid_h, device=device) + start_position position_width = torch.arange(llm_grid_w, device=device) + start_position
T_grid, H_grid, W_grid = torch.meshgrid(position_temporal, position_height, position_width, indexing="ij") vision_position_ids = torch.stack([T_grid, H_grid, W_grid], dim=0).reshape(3, -1) vision_position_ids[0] += start_position # must be after time_interval multiply return vision_position_ids
def get_rope_index( self, input_ids: torch.LongTensor, mm_token_type_ids: torch.IntTensor, image_grid_thw: torch.LongTensor | None = None, video_grid_thw: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, **kwargs, ) -> tuple[torch.Tensor, torch.Tensor]: """ Difference from Qwen2VL/Qwen2.5VL's get_rope_index: - Since Qwen3.5 use timestamps to separate videos, like <t1> <vision_start> <frame1> <vision_end> <t2> <vision_start> <frame2> <vision_end>, the video_grid_thw should also be split too.
Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`): Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2). image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**, - 0 for tokens that are **masked**.
Returns: position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`) mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`) """
# Separate video grid thw into multiple grids because timestamps are used to separate videos. if video_grid_thw is not None: video_grid_thw = torch.repeat_interleave(video_grid_thw, video_grid_thw[:, 0], dim=0) video_grid_thw[:, 0] = 1 spatial_merge_size = self.config.vision_config.spatial_merge_size
mrope_position_deltas = [] position_ids = torch.zeros( 3, input_ids.shape[0], input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device, ) grid_iters = { 1: iter(image_grid_thw) if image_grid_thw is not None else None, 2: iter(video_grid_thw) if video_grid_thw is not None else None, }
for batch_idx, current_input_ids in enumerate(input_ids): input_token_type = mm_token_type_ids[batch_idx] if attention_mask is not None: current_input_ids = current_input_ids[attention_mask[batch_idx].bool()] input_token_type = input_token_type[attention_mask[batch_idx].bool()]
input_type_group = [] for key, group in itertools.groupby(enumerate(input_token_type.tolist()), lambda x: x[1]): group = list(group) start_index = group[0][0] end_index = group[-1][0] + 1 input_type_group.append((key, start_index, end_index))
current_pos = 0 llm_pos_ids_list = [] for modality_type, start_idx, end_idx in input_type_group: # text == 0 if modality_type == 0: text_len = end_idx - start_idx llm_pos_ids_list.append( torch.arange(text_len, device=input_ids.device).view(1, -1).expand(3, -1) + current_pos ) current_pos += text_len # image == 1, video == 2 else: grid_thw = next(grid_iters[modality_type]) vision_position_ids = self.get_vision_position_ids( current_pos, grid_thw, 1, spatial_merge_size, device=input_ids.device ) llm_pos_ids_list.append(vision_position_ids) current_pos += max(grid_thw[1], grid_thw[2]) // spatial_merge_size llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) if attention_mask is not None: position_ids[:, batch_idx, attention_mask[batch_idx].bool()] = llm_positions.to(position_ids.device) else: position_ids[:, batch_idx] = llm_positions.to(position_ids.device) mrope_position_deltas.append(llm_positions.max() + 1 - len(current_input_ids)) mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1) return position_ids, mrope_position_deltas
@accepts_precomputed_kwargs(modality="video") @can_return_tuple @auto_docstring def get_video_features( self, pixel_values_videos: torch.FloatTensor, video_grid_thw: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | BaseModelOutputWithPooling: # Same implementation as for images return self.get_image_features(pixel_values_videos, video_grid_thw, **kwargs)
@accepts_precomputed_kwargs(modality="image") @can_return_tuple @auto_docstring def get_image_features( self, pixel_values: torch.FloatTensor, image_grid_thw: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | BaseModelOutputWithPooling: pixel_values = pixel_values.type(self.visual.dtype) vision_outputs = self.visual(pixel_values, grid_thw=image_grid_thw, **kwargs) split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist() vision_outputs.pooler_output = torch.split(vision_outputs.pooler_output, split_sizes)
return vision_outputs
def get_placeholder_mask( self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor | None = None, video_features: torch.FloatTensor | None = None, ): """ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is equal to the length of multimodal features. If the lengths are different, an error is raised. """ if input_ids is None: special_image_mask = inputs_embeds == self.get_input_embeddings()( torch.full((), self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device) ) special_image_mask = special_image_mask.all(-1) special_video_mask = inputs_embeds == self.get_input_embeddings()( torch.full((), self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device) ) special_video_mask = special_video_mask.all(-1) else: special_image_mask = input_ids == self.config.image_token_id special_video_mask = input_ids == self.config.video_token_id
n_image_tokens = special_image_mask.sum() special_image_mask = special_image_mask.unsqueeze(-1).to(inputs_embeds.device) if image_features is not None: torch_compilable_check( n_image_tokens * inputs_embeds.shape[-1] == image_features.numel(), f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {image_features.shape[0]}", )
n_video_tokens = special_video_mask.sum() special_video_mask = special_video_mask.unsqueeze(-1).to(inputs_embeds.device) if video_features is not None: torch_compilable_check( n_video_tokens * inputs_embeds.shape[-1] == video_features.numel(), f"Video features and video tokens do not match, tokens: {n_video_tokens}, features: {video_features.shape[0]}", ) return special_image_mask, special_video_mask
def compute_3d_position_ids( self, input_ids: torch.Tensor | None, inputs_embeds: torch.Tensor | None, image_grid_thw: torch.Tensor | None = None, video_grid_thw: torch.Tensor | None = None, attention_mask: torch.Tensor | None = None, past_key_values: torch.Tensor | None = None, mm_token_type_ids: torch.IntTensor | None = None, ) -> torch.Tensor | None: past_key_values_length = 0 if past_key_values is None else past_key_values.get_seq_length() has_multimodal = image_grid_thw is not None or video_grid_thw is not None if has_multimodal and mm_token_type_ids is None and input_ids is not None: raise ValueError( "Multimodal data was passed (via `image_grid_thw` or `video_grid_thw`) but `mm_token_type_ids` is " "missing. Please pass `mm_token_type_ids` to the model so that multimodal RoPE (M-RoPE) can be " "computed correctly. `mm_token_type_ids` is returned by the processor alongside `input_ids`." ) can_compute_mrope = input_ids is not None and mm_token_type_ids is not None and has_multimodal
if can_compute_mrope and (self.rope_deltas is None or past_key_values_length == 0): position_ids, rope_deltas = self.get_rope_index( input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, attention_mask=attention_mask, mm_token_type_ids=mm_token_type_ids, ) self.rope_deltas = rope_deltas # Use pre-calculated rope-deltas to infer correct 3D position ids during incremental # generation (past_key_values_length > 0) or when only inputs_embeds is provided (no input_ids # to recompute from). Skip when input_ids is provided without past_key_values to avoid shape # mismatches from stale rope_deltas (e.g., training forward pass after generation). elif self.rope_deltas is not None and (past_key_values_length > 0 or input_ids is None): batch_size, seq_length, _ = inputs_embeds.shape if attention_mask is not None: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids = position_ids.masked_fill(attention_mask == 0, 0) position_ids = position_ids.view(1, batch_size, -1).repeat(3, 1, 1).to(inputs_embeds.device) else: position_ids = torch.arange(past_key_values_length, past_key_values_length + seq_length) position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1).to(inputs_embeds.device) delta = self.rope_deltas.repeat_interleave(batch_size // self.rope_deltas.shape[0], dim=0) position_ids = position_ids + delta.to(device=inputs_embeds.device) else: # Can't build correct 3D positions. Let the model infer it position_ids = None return position_ids
@can_return_tuple @auto_docstring def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = None, pixel_values: torch.Tensor | None = None, pixel_values_videos: torch.FloatTensor | None = None, image_grid_thw: torch.LongTensor | None = None, video_grid_thw: torch.LongTensor | None = None, mm_token_type_ids: torch.IntTensor | None = None, mm_encoder_outputs: dict[str, BaseModelOutputWithPooling] | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | Qwen3_5ModelOutputWithPast: if (pixel_values is not None or pixel_values_videos is not None) and mm_encoder_outputs is not None: raise ValueError( "You cannot specify both pixel_values/pixel_values_videos and mm_encoder_outputs at the same time" )
if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids)
mm_encoder_outputs = mm_encoder_outputs if mm_encoder_outputs is not None else {} if mm_encoder_outputs.get("image") is None and pixel_values is not None: mm_encoder_outputs["image"] = self.get_image_features( pixel_values, image_grid_thw, return_dict=True, **kwargs )
if mm_encoder_outputs.get("video") is None and pixel_values_videos is not None: mm_encoder_outputs["video"] = self.get_video_features( pixel_values_videos, video_grid_thw, return_dict=True, **kwargs )
if mm_encoder_outputs.get("image") is not None: image_embeds = torch.cat(mm_encoder_outputs["image"].pooler_output, dim=0).to( inputs_embeds.device, inputs_embeds.dtype ) image_mask, _ = self.get_placeholder_mask( input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds ) inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
if mm_encoder_outputs.get("video") is not None: video_embeds = torch.cat(mm_encoder_outputs["video"].pooler_output, dim=0).to( inputs_embeds.device, inputs_embeds.dtype ) _, video_mask = self.get_placeholder_mask( input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds ) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
if position_ids is None: position_ids = self.compute_3d_position_ids( input_ids=input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, inputs_embeds=inputs_embeds, attention_mask=attention_mask, past_key_values=past_key_values, mm_token_type_ids=mm_token_type_ids, )
outputs = self.language_model( input_ids=None, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, **kwargs, ) return Qwen3_5ModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, rope_deltas=self.rope_deltas, )
@auto_docstringclass Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_gather_output"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} _fsdp_plan = {"lm_head": "keep_full_weight"} config: Qwen3_5TextConfig _keys_to_ignore_on_load_unexpected = [r"^mtp.*", r"^model.visual.*"]
def __init__(self, config): super().__init__(config) self.model = Qwen3_5TextModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing self.post_init()
@can_return_tuple @auto_docstring def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, logits_to_keep: int | torch.Tensor = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: r""" Example:
```python >>> from transformers import AutoTokenizer, Qwen3_5ForCausalLM
>>> model = Qwen3_5ForCausalLM.from_pretrained("Qwen/Qwen3_5-8B") >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3_5-8B")
>>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, **kwargs, )
hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
class Qwen3_5ForTokenClassification(GenericForTokenClassification, Qwen3_5PreTrainedModel): config: Qwen3_5Config
@auto_docstring@dataclassclass Qwen3_5CausalLMOutputWithPast(CausalLMOutputWithPast): r""" rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*): The rope index difference between sequence length and multimodal rope. The attribute is deprecated and will be removed in v5.20, use `model.base_model.rope_deltas` instead. """
rope_deltas: torch.LongTensor | None = None
class Qwen3_5ForConditionalGeneration(Qwen3_5PreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"} # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False
def __init__(self, config): super().__init__(config) self.model = Qwen3_5Model(config) self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
self.post_init()
@auto_docstring def get_video_features( self, pixel_values_videos: torch.FloatTensor, video_grid_thw: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | BaseModelOutputWithPooling: r""" pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input videos. """ return self.model.get_video_features(pixel_values_videos, video_grid_thw, **kwargs)
@auto_docstring def get_image_features( self, pixel_values: torch.FloatTensor, image_grid_thw: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | BaseModelOutputWithPooling: r""" pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input images. """ return self.model.get_image_features(pixel_values, image_grid_thw, **kwargs)
@can_return_tuple @auto_docstring def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, pixel_values: torch.Tensor | None = None, pixel_values_videos: torch.FloatTensor | None = None, image_grid_thw: torch.LongTensor | None = None, video_grid_thw: torch.LongTensor | None = None, mm_token_type_ids: torch.IntTensor | None = None, logits_to_keep: int | torch.Tensor = 0, mm_encoder_outputs: dict[str, BaseModelOutputWithPooling] | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | Qwen3_5CausalLMOutputWithPast: r""" Example:
```python >>> from transformers import AutoProcessor, Qwen3_5ForConditionalGeneration
>>> model = Qwen3_5ForConditionalGeneration.from_pretrained("Qwen/Qwen3-VL-8B-Instruct") >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL-8B-Instruct")
>>> messages = [ { "role": "user", "content": [ { "type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", }, {"type": "text", "text": "Describe the image."}, ], } ]
>>> inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" )
>>> # Generate >>> generated_ids = model.generate(**inputs, max_new_tokens=1024) >>> generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)] >>> output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] >>> print(output_text) ``` """
outputs = self.model( input_ids=input_ids, pixel_values=pixel_values, pixel_values_videos=pixel_values_videos, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, mm_token_type_ids=mm_token_type_ids, mm_encoder_outputs=mm_encoder_outputs, **kwargs, )
hidden_states = outputs[0]
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None if labels is not None: loss = self.loss_function( logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs )
return Qwen3_5CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, rope_deltas=outputs.rope_deltas, )
def _prepare_position_ids_for_generation(self, inputs_tensor, model_kwargs): # Overwritten -- requires 3D position ids
text_positions = super()._prepare_position_ids_for_generation(inputs_tensor, model_kwargs)
# Early exit in case we are continuing generation from past kv past_length = 0 if (cache := model_kwargs.get("past_key_values")) is not None: past_length = cache.get_seq_length() if past_length != 0 and self.model.rope_deltas is not None: position_ids = text_positions[None, ...] + self.model.rope_deltas return position_ids
# Otherwise compute 3d position ids for vision tokens and concat with text position ids if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0: inputs_tensor = model_kwargs["input_ids"]
is_input_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long] if ( is_input_ids and model_kwargs.get("mm_token_type_ids") is not None and (model_kwargs.get("image_grid_thw") is not None or model_kwargs.get("video_grid_thw") is not None) ): model_kwargs = {k: v for k, v in model_kwargs.items() if k != "input_ids"} vision_positions, rope_deltas = self.model.get_rope_index(inputs_tensor, **model_kwargs) self.model.rope_deltas = rope_deltas else: vision_positions = text_positions.unsqueeze(0).expand(3, -1, -1) self.model.rope_deltas = torch.zeros( inputs_tensor.shape[0], 1, dtype=torch.long, device=inputs_tensor.device )
# Concatenate "text + vision" positions into [4, bs, seq-len] text_positions = text_positions[None, ...] position_ids = torch.cat([text_positions, vision_positions], dim=0)
return position_ids
class Qwen3_5TextForSequenceClassification(GenericForSequenceClassification, Qwen3_5PreTrainedModel): config: Qwen3_5TextConfig input_modalities = ("text",)
class Qwen3_5ForSequenceClassification(GenericForSequenceClassification, Qwen3_5PreTrainedModel): def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, pixel_values: torch.Tensor | None = None, pixel_values_videos: torch.FloatTensor | None = None, image_grid_thw: torch.LongTensor | None = None, video_grid_thw: torch.LongTensor | None = None, mm_token_type_ids: torch.IntTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> SequenceClassifierOutputWithPast: return super().forward( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, pixel_values=pixel_values, pixel_values_videos=pixel_values_videos, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, mm_token_type_ids=mm_token_type_ids, **kwargs, )
__all__ = [ "Qwen3_5VisionModel", "Qwen3_5TextModel", "Qwen3_5Model", "Qwen3_5ForCausalLM", "Qwen3_5TextForSequenceClassification", "Qwen3_5ForSequenceClassification", "Qwen3_5ForTokenClassification", "Qwen3_5ForConditionalGeneration", "Qwen3_5PreTrainedModel",]1234"""Qev: open System One decision model and TypeSafe-compatible server."""__version__ = "0.1.0"
from .client import Choice, Client, Noul, Score1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Answer assembly: probabilities to typed answers, with TypeSafe's confidence formulas.
The two confidence functions are ported from typesafe-ai/system-one-adapter-python(MIT License, Copyright (c) 2026 TypeSafe AI) and verified against Jev's published answers(mean absolute error 0.013 for Choice, 0.005 for Score, within two-decimal rounding)."""from __future__ import annotations
from typing import Any, Sequence
from .schema import ChoiceAnswer, NoulAnswer, ScoreAnswer
def _normalize(probs: Sequence[float]) -> list[float]: total = float(sum(probs)) if total <= 0: return [1.0 / len(probs)] * len(probs) return [float(p) / total for p in probs]
def choice_confidence(probs: Sequence[float]) -> float: """Peak probability rescaled from uniform (0) to certainty (1).""" if len(probs) == 1: return 1.0 p = _normalize(probs) uniform = 1.0 / len(p) return (max(p) - uniform) / (1.0 - uniform)
def score_confidence(probs: Sequence[float]) -> float: """One minus the probability-weighted mean absolute deviation from the modal level, normalised by the mean absolute deviation of the uniform distribution over the levels.""" if len(probs) == 1: return 1.0 p = _normalize(probs) k = len(p) mode = max(range(k), key=p.__getitem__) distance = sum(pi * abs(i - mode) for i, pi in enumerate(p)) center = (k - 1) / 2 uniform_mad = sum(abs(i - center) for i in range(k)) / k return max(0.0, 1.0 - distance / uniform_mad)
def expected_score(probs: Sequence[float]) -> float: p = _normalize(probs) return float(sum(i * pi for i, pi in enumerate(p)))
def _round(x: float, nd: int = 6) -> float: return float(round(x, nd))
def make_noul(p_yes: float) -> NoulAnswer: return NoulAnswer(noul=_round(min(1.0, max(0.0, float(p_yes)))))
def make_choice(options: Sequence[str], probs: Sequence[float]) -> ChoiceAnswer: p = _normalize(probs) best = max(range(len(p)), key=p.__getitem__) return ChoiceAnswer( choice=options[best], probabilities={o: _round(pi) for o, pi in zip(options, p)}, confidence=_round(choice_confidence(p)), )
def make_score(levels: Sequence[Any], probs: Sequence[float]) -> ScoreAnswer: p = _normalize(probs) return ScoreAnswer( score=_round(expected_score(p)), legend={str(i): lvl for i, lvl in enumerate(levels)}, probabilities={str(i): _round(pi) for i, pi in enumerate(p)}, confidence=_round(score_confidence(p)), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Calibration: temperatures per (primitive, option count), fitting, and probability metrics."""from __future__ import annotations
import jsonimport loggingimport mathfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Sequence
@dataclassclass Calibration: """Temperature table. Keys are "kind" or "kind:K". Missing keys fall back to the primitive-level temperature, then to 1.0."""
temperatures: dict[str, float] = field(default_factory=dict) source: str = "none"
def temperature(self, kind: str, k: int) -> float: return self.temperatures.get(f"{kind}:{k}", self.temperatures.get(kind, 1.0))
@classmethod def load(cls, path: str | Path) -> "Calibration": data = json.loads(Path(path).read_text()) return cls(temperatures={k: float(v) for k, v in data.get("temperatures", {}).items()}, source=str(path))
def save(self, path: str | Path) -> None: from .prompt import PROMPT_VERSION
Path(path).write_text(json.dumps({"temperatures": self.temperatures, "source": self.source, "prompt_version": PROMPT_VERSION}, indent=2))
def softmax(logits: Sequence[float], temperature: float = 1.0) -> list[float]: z = [float(x) / temperature for x in logits] m = max(z) w = [math.exp(x - m) for x in z] s = sum(w) return [x / s for x in w]
def fit_temperature(logits: Sequence[Sequence[float]], targets: Sequence[Sequence[float]], lo: float = 0.05, hi: float = 50.0, iters: int = 60) -> float: """Fit one scalar temperature by minimising cross-entropy against (possibly soft) targets. Golden-section search on log T; no torch dependency so it runs anywhere.""" def nll(t: float) -> float: total = 0.0 for z, y in zip(logits, targets): p = softmax(z, t) total -= sum(yi * math.log(max(pi, 1e-12)) for yi, pi in zip(y, p)) return total / max(len(logits), 1)
a, b = math.log(lo), math.log(hi) gr = (math.sqrt(5) - 1) / 2 c, d = b - gr * (b - a), a + gr * (b - a) fc, fd = nll(math.exp(c)), nll(math.exp(d)) for _ in range(iters): if fc < fd: b, d, fd = d, c, fc c = b - gr * (b - a) fc = nll(math.exp(c)) else: a, c, fc = c, d, fd d = a + gr * (b - a) fd = nll(math.exp(d)) t = math.exp((a + b) / 2) if t >= hi * 0.99 or t <= lo * 1.01: logging.getLogger("qev.calibrate").warning( "temperature fit hit the %s bound (T=%.4f) on %d rows; the slot logits likely carry no signal for this group", "upper" if t >= hi * 0.99 else "lower", t, len(logits)) return t
def ece(confidences: Sequence[float], correct: Sequence[float], n_bins: int = 15) -> float: n = len(confidences) if n == 0: return 0.0 total = 0.0 for b in range(n_bins): lo, hi = b / n_bins, (b + 1) / n_bins idx = [i for i, c in enumerate(confidences) if (lo < c <= hi) or (b == 0 and c <= lo)] if idx: avg_conf = sum(confidences[i] for i in idx) / len(idx) avg_acc = sum(correct[i] for i in idx) / len(idx) total += len(idx) / n * abs(avg_conf - avg_acc) return total
def adaptive_ece(confidences: Sequence[float], correct: Sequence[float], n_bins: int = 15) -> float: n = len(confidences) if n == 0: return 0.0 order = sorted(range(n), key=lambda i: confidences[i]) total = 0.0 size = max(1, n // n_bins) for start in range(0, n, size): idx = order[start:start + size] avg_conf = sum(confidences[i] for i in idx) / len(idx) avg_acc = sum(correct[i] for i in idx) / len(idx) total += len(idx) / n * abs(avg_conf - avg_acc) return total
def brier(probs: Sequence[float], target: Sequence[float]) -> float: return sum((p - t) ** 2 for p, t in zip(probs, target))
def nll(probs: Sequence[float], target: Sequence[float]) -> float: return -sum(t * math.log(max(p, 1e-12)) for p, t in zip(probs, target))
def tvd(p: Sequence[float], q: Sequence[float]) -> float: return 0.5 * sum(abs(a - b) for a, b in zip(p, q))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Tiny HTTP client for any System One endpoint (Qev or TypeSafe).
from qev import Client, Choice, Score, Noul c = Client("http://localhost:8000") r = c.system_one(state, {"dept": Choice("Which team?", {"billing": "...", "tech": "..."})}) r.answers["dept"].choice"""from __future__ import annotations
import jsonimport osimport urllib.requestfrom dataclasses import dataclass, fieldfrom typing import Any
@dataclassclass Noul: instructions: Any = None criteria: dict[str, Any] | None = None
def to_dict(self) -> dict[str, Any]: d: dict[str, Any] = {"type": "noul"} if self.instructions is not None: d["instructions"] = self.instructions if self.criteria is not None: d["criteria"] = self.criteria return d
@dataclassclass Choice: instructions: Any criteria: dict[str, Any]
def to_dict(self) -> dict[str, Any]: return {"type": "choice", "instructions": self.instructions, "criteria": self.criteria}
@dataclassclass Score: instructions: Any criteria: list[Any]
def to_dict(self) -> dict[str, Any]: return {"type": "score", "instructions": self.instructions, "criteria": self.criteria}
class _Answer: def __init__(self, data: dict[str, Any]) -> None: self.raw = data for k, v in data.items(): setattr(self, k, v)
def __repr__(self) -> str: return f"Answer({json.dumps(self.raw, ensure_ascii=False)})"
@dataclassclass Response: model: str answers: dict[str, _Answer] usage: dict[str, Any] request_id: str | None = None meta: dict[str, Any] = field(default_factory=dict)
@property def nouls(self) -> dict[str, _Answer]: return {k: v for k, v in self.answers.items() if v.raw["type"] == "noul"}
@property def choices(self) -> dict[str, _Answer]: return {k: v for k, v in self.answers.items() if v.raw["type"] == "choice"}
@property def scores(self) -> dict[str, _Answer]: return {k: v for k, v in self.answers.items() if v.raw["type"] == "score"}
class Client: def __init__(self, base_url: str | None = None, api_key: str | None = None, model: str = "jev-latest", timeout: float = 120.0) -> None: self.base_url = (base_url or os.environ.get("QEV_BASE_URL") or os.environ.get("TYPESAFE_BASE_URL") or "http://localhost:8000").rstrip("/") self.api_key = api_key or os.environ.get("TYPESAFE_API_KEY") or "local" self.model = model self.timeout = timeout
def _post(self, path: str, body: dict[str, Any]) -> tuple[dict[str, Any], dict[str, str]]: req = urllib.request.Request(self.base_url + path, data=json.dumps(body).encode(), method="POST", headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}", "User-Agent": "qev-client"}) with urllib.request.urlopen(req, timeout=self.timeout) as resp: return json.loads(resp.read()), dict(resp.headers)
def _get(self, path: str) -> dict[str, Any]: req = urllib.request.Request(self.base_url + path, headers={"Authorization": f"Bearer {self.api_key}", "User-Agent": "qev-client"}) with urllib.request.urlopen(req, timeout=self.timeout) as resp: return json.loads(resp.read())
def system_one(self, state: Any, questions: dict[str, Any], model: str | None = None, media: list[dict] | None = None, **params: Any) -> Response: """`media` (OneJev servers): images and videos the state refers to as <image:N> / <video:N>, see qev.media.""" qs = {k: (v.to_dict() if hasattr(v, "to_dict") else v) for k, v in questions.items()} path = "/v1/systemone" if params: path += "?" + "&".join(f"{k}={v}" for k, v in params.items()) body = {"state": state, "model": model or self.model, "questions": qs} if media is not None: body["media"] = media data, headers = self._post(path, body) return Response(model=data["model"], answers={k: _Answer(v) for k, v in data["answers"].items()}, usage=data.get("usage", {}), request_id=headers.get("x-typesafe-request-id"), meta=data.get("qev", {}))
def models(self) -> list[dict[str, Any]]: return self._get("/v1/models")["models"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Rendering: request -> shared prefix text + one suffix per question + answer slots.
Everything the model sees is produced here, so this file is the single place to audit for
leakage of anything the model should not see (question ids, gold labels, internal bookkeeping).
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import Any, Sequence
from .schema import ChoiceQuestion, NoulQuestion, Question, ScoreQuestion
PROMPT_VERSION = "qev-labels-v2"
SYSTEM_PROMPT = (
"Apply the question to the state. Choose exactly one of the listed options. "
"Respond with only its uppercase letter, with no explanation or reasoning."
)
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
_NOT_ONE_TOKEN = {"BQ", "BZ", "CJ", "CQ", "CZ", "DQ", "DZ", "EJ", "EY", "FJ", "FQ", "FV", "FZ", "GJ", "GK", "GQ", "GZ",
"HJ", "IY", "JF", "JG", "JH", "JL", "JN", "JQ"}
SLOT_LABELS: tuple[str, ...] = tuple(
list(LETTERS) + [a + b for a in LETTERS for b in LETTERS if a + b not in _NOT_ONE_TOKEN][: 256 - len(LETTERS)])
MAX_SLOTS = len(SLOT_LABELS)
@dataclass(frozen=True)
class PromptStyle:
"""Wording and layout knobs. The default instance is the frozen production template; other
instances exist only for ablations."""
name: str = PROMPT_VERSION
system: str = SYSTEM_PROMPT
layout: str = "tagged"
show_names: bool = True
question_header: str = "Question:"
score_header: str = "Rate the state:"
answer_line: str = "Answer with one letter: {letters}."
answer_line_many: str = "Answer with one label: {letters}."
DEFAULT_STYLE = PromptStyle()
NOUL_DEFAULT_INSTRUCTIONS = "Is the statement true, or is the answer to the question yes?"
NOUL_DEFAULT_TRUE = "the statement is true / the answer is yes"
NOUL_DEFAULT_FALSE = "the statement is false / the answer is no"
def render_entry(entry: Any) -> str:
"""Render an instructions / criteria entry (string, object, array or null) as text."""
if entry is None:
return ""
if isinstance(entry, str):
return entry.strip()
return json.dumps(entry, ensure_ascii=False, indent=2)
def render_state(state: Any) -> str:
if state is None:
return ""
if isinstance(state, str):
return state
return json.dumps(state, ensure_ascii=False, indent=2)
@dataclass
class RenderedQuestion:
"""One branch: the suffix text and the labels its slots map to."""
qid: str
kind: str
labels: list[str]
descriptions: list[Any]
suffix: str
option_spans: list[tuple[int, int]] | None = None
n_slots: int = field(init=False)
def __post_init__(self) -> None:
self.n_slots = len(self.labels)
def _options_lines(names: Sequence[str], descriptions: Sequence[Any], show_names: bool = True) -> list[str]:
lines = []
for letter, name, desc in zip(SLOT_LABELS, names, descriptions):
text = render_entry(desc)
if name is None or (not show_names and text):
lines.append(f"{letter}. {text}")
elif text:
lines.append(f"{letter}. {name}: {text}")
else:
lines.append(f"{letter}. {name}")
return lines
def _options_block(names: Sequence[str], descriptions: Sequence[Any], show_names: bool = True) -> str:
return "\n".join(_options_lines(names, descriptions, show_names))
def render_question(qid: str, q: Question, order: Sequence[int] | None = None, style: PromptStyle = DEFAULT_STYLE) -> RenderedQuestion:
"""Render one question into a suffix. `order` optionally permutes the slot order (used for
permutation debiasing and training augmentation); labels/descriptions follow the permutation."""
if isinstance(q, NoulQuestion):
kind = "noul"
instructions = render_entry(q.instructions) or NOUL_DEFAULT_INSTRUCTIONS
crit = q.criteria
t = render_entry(crit.true) if crit and crit.true is not None else NOUL_DEFAULT_TRUE
f = render_entry(crit.false) if crit and crit.false is not None else NOUL_DEFAULT_FALSE
labels, names, descs = ["yes", "no"], ["yes", "no"], [t, f]
elif isinstance(q, ChoiceQuestion):
kind = "choice"
instructions = render_entry(q.instructions) or "Which option applies to the state?"
labels = list(q.criteria.keys())
names = list(labels)
descs = [q.criteria[k] for k in labels]
elif isinstance(q, ScoreQuestion):
kind = "score"
instructions = render_entry(q.instructions) or "Which level describes the state?"
labels = [str(i) for i in range(len(q.criteria))]
names = [f"level {i}" for i in range(len(q.criteria))]
descs = list(q.criteria)
else:
raise TypeError(f"unknown question type {type(q)}")
if len(labels) > MAX_SLOTS:
raise ValueError(f"{len(labels)} options exceed the {MAX_SLOTS} slots of prompt {PROMPT_VERSION}")
if order is not None:
labels = [labels[i] for i in order]
names = [names[i] for i in order]
descs = [descs[i] for i in order]
letters = list(SLOT_LABELS[: len(labels)])
spans = None
if style.layout == "json":
payload = {"criterion": instructions,
"options": [{"letter": l, "description": (f"{n}: {render_entry(d)}" if (style.show_names and n is not None and render_entry(d)) else (render_entry(d) or n))}
for l, n, d in zip(letters, names, descs)]}
suffix = json.dumps(payload, ensure_ascii=False)[1:]
else:
header = style.question_header if kind != "score" else style.score_header
head = f"{header} {instructions}\n\nOptions:\n"
lines = _options_lines(names, descs, style.show_names)
spans, pos = [], len(head)
for line in lines:
spans.append((pos, pos + len(line)))
pos += len(line) + 1
suffix = (
head + "\n".join(lines) + "\n\n"
+ (style.answer_line if len(letters) <= len(LETTERS) else style.answer_line_many).format(letters=", ".join(letters))
)
return RenderedQuestion(qid=qid, kind=kind, labels=labels, descriptions=descs, suffix=suffix, option_spans=spans)
def state_block(state: Any, style: PromptStyle = DEFAULT_STYLE) -> str:
if style.layout == "json":
return "{" + json.dumps({"evidence": state}, ensure_ascii=False)[1:-1] + ", "
return f"<state>\n{render_state(state)}\n</state>\n\n"
def build_messages(state: Any, suffix: str, style: PromptStyle = DEFAULT_STYLE) -> list[dict[str, str]]:
"""Chat messages for one branch. The user turn is `state_block + suffix`, so every branch of a
request shares the same prefix up to the end of the state block."""
return [
{"role": "system", "content": style.system},
{"role": "user", "content": state_block(state, style) + suffix},
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269"""Readout variants, shared by training (train.common / train.sft) and serving (qev.engine).
attention:
causal the base model's mask.
noncausal in the full-attention layers every token attends bidirectionally within its block and causally to
earlier blocks. A rendered prompt has two blocks: the shared prefix (system turn and state block) and
the question suffix (question, options, answer line, generation prompt). The prefix never sees a
suffix, so its cache is still shared exactly by all questions of a request, and one forward of a
suffix scores all of its options. The GatedDeltaNet (linear-attention) layers are recurrent and stay
causal.
readout:
slot_lm softmax over the LM-head logits of the slot letters at the answer position.
head a learned head over the final (normed) hidden states:
score_i = <w_i, h_ans> + <W_q h_ans, W_k mean(h over option i's line)> / sqrt(d)
w has one row per slot and starts as the LM-head rows of the slot letters, W_k starts at zero, so the
untrained head reproduces slot_lm exactly; the pointer term scores each option by its content.
Both settings are recorded next to the weights, so a checkpoint is always served the way it was trained. The
attention mask is declared per layer type under `modeling_overrides` in `config.json`, where serving stacks
read it; `readout.json` holds the rest. Checkpoints without the overrides block carry `attention` in `readout.json`.
"""
from __future__ import annotations
import bisect
import contextlib
import contextvars
import importlib
import json
import math
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Sequence
import torch
from .prompt import MAX_SLOTS
CONFIG_FILE = "readout.json"
MODEL_CONFIG_FILE = "config.json"
OVERRIDES_KEY = "modeling_overrides"
FULL_ATTENTION_MASK = {"causal": "causal", "noncausal": "block_bidirectional"}
HEAD_FILE = "readout_head.pt"
ATTENTION = ("causal", "noncausal")
READOUT = ("slot_lm", "head")
@dataclass
class ReadoutConfig:
attention: str = "causal"
readout: str = "slot_lm"
head_dim: int = 256
n_slots: int = MAX_SLOTS
def __post_init__(self) -> None:
if self.attention not in ATTENTION:
raise ValueError(f"attention must be one of {ATTENTION}, got {self.attention!r}")
if self.readout not in READOUT:
raise ValueError(f"readout must be one of {READOUT}, got {self.readout!r}")
@property
def noncausal(self) -> bool:
return self.attention == "noncausal"
@property
def head(self) -> bool:
return self.readout == "head"
@property
def needs_layout(self) -> bool:
return self.noncausal or self.head
@classmethod
def load(cls, model_dir: str | Path) -> "ReadoutConfig":
path, model_path = Path(model_dir) / CONFIG_FILE, Path(model_dir) / MODEL_CONFIG_FILE
fields = json.loads(path.read_text()) if path.exists() else {}
overrides = json.loads(model_path.read_text()).get(OVERRIDES_KEY) if model_path.exists() else None
if overrides:
mask = overrides["attention"]["full_attention"]
attention = {v: k for k, v in FULL_ATTENTION_MASK.items()}.get(mask)
if attention is None:
raise ValueError(f"unsupported full_attention mask {mask!r} in {model_path}")
if fields.get("attention", attention) != attention:
raise ValueError(f"{path} says attention {fields['attention']!r} but {model_path} says {mask!r}")
fields["attention"] = attention
return cls(**fields)
def save(self, model_dir: str | Path) -> None:
fields = asdict(self)
model_path = Path(model_dir) / MODEL_CONFIG_FILE
if model_path.exists(): # LoRA adapters have no config.json; their readout.json keeps the attention
attention = fields.pop("attention")
config = json.loads(model_path.read_text())
config[OVERRIDES_KEY] = {"attention": {"full_attention": FULL_ATTENTION_MASK[attention],
"linear_attention": "causal"}, **fields}
model_path.unlink() # may be a symlink to the source checkpoint (model_v5/mkvariant.py)
model_path.write_text(json.dumps(config, indent=2) + "\n")
(Path(model_dir) / CONFIG_FILE).write_text(json.dumps(fields, indent=2))
_BLOCKS: contextvars.ContextVar = contextvars.ContextVar("qev_readout_blocks", default=None)
def install_noncausal(model) -> None:
"""Route block ids (set with `blocks`) into the full-attention mask of the model's modeling module. Outside a
`blocks` context the model is unchanged. Needs a mask-based attention implementation (sdpa, eager, flex)."""
impl = getattr(model.config.get_text_config(), "_attn_implementation", None) or model.config._attn_implementation
if impl not in ("sdpa", "eager", "flex_attention"):
raise ValueError(f"noncausal attention needs sdpa, eager or flex_attention, not {impl}")
mod = importlib.import_module(type(model).__module__)
if getattr(mod, "_qev_noncausal", False):
return
if not hasattr(mod, "create_causal_mask"):
raise ValueError(f"{mod.__name__} builds no causal mask to extend")
original = mod.create_causal_mask
def create_causal_mask(*args, **kwargs):
ids = _BLOCKS.get()
if ids is not None and kwargs.get("block_sequence_ids") is None:
kwargs["block_sequence_ids"] = ids
return original(*args, **kwargs)
mod.create_causal_mask = create_causal_mask
mod._qev_noncausal = True
@contextlib.contextmanager
def blocks(ids):
"""Block ids [B, kv_length] over absolute positions (cached prefix included); None leaves the mask causal."""
token = _BLOCKS.set(ids)
try:
yield
finally:
_BLOCKS.reset(token)
def block_ids(prefix_lens: Sequence[int], lengths: Sequence[int], width: int, device) -> torch.Tensor:
"""0 on the prefix, 1 on the suffix, -1 on right padding (causal, and masked as a key anyway)."""
pos = torch.arange(width, device=device)[None]
p = torch.tensor(list(prefix_lens), device=device)[:, None]
n = torch.tensor(list(lengths), device=device)[:, None]
return torch.where(pos < p, 0, torch.where(pos < n, 1, -1))
def token_layout(tokenizer, prompt: str, suffix_start: int, option_spans: Sequence[tuple[int, int]] | None):
"""Token ids of `prompt`, the prefix length (tokens that end at or before the suffix) and each option line's
token span [start, end), from the tokenizer's character offsets. Option spans are characters of the prompt."""
enc = tokenizer(prompt, add_special_tokens=False, return_offsets_mapping=True)
ids, offs = enc["input_ids"], enc["offset_mapping"]
ends = [e for _, e in offs]
starts = [s for s, _ in offs]
prefix = bisect.bisect_right(ends, suffix_start)
spans = []
for cs, ce in option_spans or []:
a = bisect.bisect_right(ends, cs)
b = bisect.bisect_left(starts, ce)
if b <= a:
raise ValueError(f"option span {cs}:{ce} covers no token")
spans.append((a, b))
return ids, prefix, spans
class ReadoutHead(torch.nn.Module):
def __init__(self, hidden: int, n_slots: int = MAX_SLOTS, head_dim: int = 256):
super().__init__()
self.slot = torch.nn.Parameter(torch.zeros(n_slots, hidden))
self.q = torch.nn.Linear(hidden, head_dim, bias=False)
self.k = torch.nn.Linear(hidden, head_dim, bias=False)
torch.nn.init.normal_(self.q.weight, std=hidden ** -0.5)
torch.nn.init.zeros_(self.k.weight)
@classmethod
def from_lm_head(cls, lm_head_weight, slot_ids: Sequence[int], head_dim: int) -> "ReadoutHead":
rows = lm_head_weight.detach()[list(slot_ids)].float()
head = cls(rows.shape[1], rows.shape[0], head_dim)
with torch.no_grad():
head.slot.copy_(rows.to(head.slot.device))
return head
def forward(self, h_ans, h_opt):
"""h_ans [B, H], h_opt [B, K, H] -> scores [B, K] (fp32)."""
h_ans, h_opt = h_ans.float(), h_opt.float()
k = h_opt.shape[1]
slot = h_ans @ self.slot[:k].T
ptr = torch.einsum("bd,bkd->bk", self.q(h_ans), self.k(h_opt)) / math.sqrt(self.q.out_features)
return slot + ptr
def pool_options(hidden, spans: Sequence[Sequence[tuple[int, int]]], kmax: int):
"""Mean of hidden [B, T, H] over each option's token span -> [B, kmax, H] fp32 (zeros past a row's options)."""
bsz, _, dim = hidden.shape
dev = hidden.device
rows, toks, segs = [], [], []
for b, sp in enumerate(spans):
for k, (s, e) in enumerate(sp):
n = e - s
rows.append(torch.full((n,), b, dtype=torch.long))
toks.append(torch.arange(s, e, dtype=torch.long))
segs.append(torch.full((n,), b * kmax + k, dtype=torch.long))
rows, toks, segs = (torch.cat(x).to(dev) for x in (rows, toks, segs))
flat = hidden[rows, toks].float()
total = torch.zeros(bsz * kmax, dim, dtype=torch.float32, device=dev).index_add(0, segs, flat)
count = torch.zeros(bsz * kmax, dtype=torch.float32, device=dev).index_add(
0, segs, torch.ones_like(segs, dtype=torch.float32))
return (total / count.clamp(min=1)[:, None]).view(bsz, kmax, dim)
def final_norm(model):
"""The final norm of a (possibly multimodal) Qwen-style decoder: its output is the readout hidden state."""
inner = getattr(model, "model", model)
inner = getattr(inner, "language_model", inner)
norm = getattr(inner, "norm", None)
if norm is None:
raise ValueError(f"cannot find the final norm of {type(model).__name__}")
return norm
class HiddenCapture:
"""Keeps the final-norm output of the latest forward (with its graph, so the head trains the backbone)."""
def __init__(self, model):
self.value = None
self.handle = final_norm(model).register_forward_hook(self._hook)
def _hook(self, module, args, output):
self.value = output
def pop(self):
out, self.value = self.value, None
if out is None:
raise RuntimeError("no hidden state captured; the forward did not reach the final norm")
return out
@dataclass
class Readout:
"""A model's readout at runtime: its config, and for `head` the head module and the hidden-state hook."""
config: ReadoutConfig
head: ReadoutHead | None = None
capture: HiddenCapture | None = None
@classmethod
def attach(cls, model, config: ReadoutConfig, slot_ids: Sequence[int] | None = None,
head_path: str | Path | None = None, device=None) -> "Readout":
"""Install the variant on `model`. A head is loaded from `head_path` when given, else initialised from the
model's LM-head rows of `slot_ids` (call before the model is sharded)."""
if config.noncausal:
install_noncausal(model)
if not config.head:
return cls(config)
if head_path is not None:
state = torch.load(head_path, map_location="cpu", weights_only=True)
head = ReadoutHead(state["slot"].shape[1], state["slot"].shape[0], state["q.weight"].shape[0])
head.load_state_dict(state)
else:
head = ReadoutHead.from_lm_head(model.get_output_embeddings().weight, slot_ids[: config.n_slots],
config.head_dim)
head = head.to(device or next(model.parameters()).device)
return cls(config, head, HiddenCapture(model))
def save(self, out_dir: str | Path) -> None:
self.config.save(out_dir)
if self.head is not None:
torch.save({k: v.detach().cpu() for k, v in self.head.state_dict().items()}, Path(out_dir) / HEAD_FILE)
@property
def max_slots(self) -> int:
return self.config.n_slots123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Request and response types for the TypeSafe-compatible System One API.
Shapes follow TypeSafe's public OpenAPI description (notes/typesafe_openapi.json) and thebehaviour of the official Python SDK (msgspec structs). Extra keys are tolerated everywhere;Score legend and probability keys are integer-parseable strings."""from __future__ import annotations
from typing import Any, Literal, Union
from pydantic import BaseModel, ConfigDict, Field, model_validator
Entry = Union[str, dict[str, Any], list[Any], None]
MAX_CHOICE_OPTIONS = 255MAX_SCORE_LEVELS = 10
class _Lenient(BaseModel): model_config = ConfigDict(extra="allow")
class NoulCriteria(_Lenient): true: Entry = None false: Entry = None
class NoulQuestion(_Lenient): type: Literal["noul"] instructions: Entry = None criteria: NoulCriteria | None = None
class ChoiceQuestion(_Lenient): type: Literal["choice"] instructions: Entry = None criteria: dict[str, Entry]
@model_validator(mode="after") def _check(self) -> "ChoiceQuestion": if not self.criteria: raise ValueError("choice question needs at least one option in criteria") if len(self.criteria) > MAX_CHOICE_OPTIONS: raise ValueError(f"choice question has {len(self.criteria)} options, maximum is {MAX_CHOICE_OPTIONS}") return self
class ScoreQuestion(_Lenient): type: Literal["score"] instructions: Entry = None criteria: list[Entry]
@model_validator(mode="after") def _check(self) -> "ScoreQuestion": if not self.criteria: raise ValueError("score question needs at least one level in criteria") if len(self.criteria) > MAX_SCORE_LEVELS: raise ValueError(f"score question has {len(self.criteria)} levels, maximum is {MAX_SCORE_LEVELS}") return self
Question = Union[NoulQuestion, ChoiceQuestion, ScoreQuestion]
class SystemOneRequest(_Lenient): state: Any = None model: str = "jev-latest" questions: dict[str, Question] = Field(discriminator=None)
@model_validator(mode="after") def _check(self) -> "SystemOneRequest": if not self.questions: raise ValueError("at least one question is required") return self
class NoulAnswer(BaseModel): type: Literal["noul"] = "noul" noul: float
class ChoiceAnswer(BaseModel): type: Literal["choice"] = "choice" choice: str probabilities: dict[str, float] confidence: float
class ScoreAnswer(BaseModel): type: Literal["score"] = "score" score: float legend: dict[str, Entry] probabilities: dict[str, float] confidence: float
Answer = Union[NoulAnswer, ChoiceAnswer, ScoreAnswer]
class Usage(BaseModel): input_tokens: int output_tokens: int
class SystemOneResponse(BaseModel): model: str answers: dict[str, Answer] usage: Usage
class ModelMetadata(BaseModel): name: str description: str release_date: str
class ModelMetadataList(BaseModel): models: list[ModelMetadata]1"""OneJev training: fine-tuning at the answer-slot readout position, calibration and evaluation."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676"""Shared pieces for training, calibration and heldout evaluation.
Every string the model sees is produced by qev.prompt, exactly as qev.engine does it,
so a checkpoint trained here renders identically when served.
"""
from __future__ import annotations
import json
import logging
import math
import random
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable, Sequence
from qev.prompt import SLOT_LABELS, build_messages, render_question
from qev.schema import ChoiceQuestion, NoulQuestion, Question, ScoreQuestion
log = logging.getLogger("train.common")
KINDS = ("noul", "choice", "score")
def load_rows(path: str | Path, limit: int | None = None, split: str | None = None) -> list[dict]:
"""Read the unified JSONL example format of DESIGN.md 4.1."""
rows: list[dict] = []
with open(path, "r", encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
row = json.loads(line)
if split is not None and row.get("split") != split:
continue
rows.append(row)
if limit is not None and len(rows) >= limit:
break
return rows
def build_question(qdict: dict) -> Question:
"""Dict to the pydantic question model that qev.prompt.render_question expects."""
kind = qdict.get("type")
if kind == "noul":
return NoulQuestion(**qdict)
if kind == "choice":
return ChoiceQuestion(**qdict)
if kind == "score":
return ScoreQuestion(**qdict)
raise ValueError(f"unknown question type {kind!r}")
def target_vector(target: dict[str, float], labels: Sequence[str]) -> list[float]:
"""Target probabilities in slot order. Labels come from the rendered question, so a permuted
rendering permutes the target for free."""
vec = [float(target.get(lbl, 0.0)) for lbl in labels]
total = sum(vec)
if total <= 0:
raise ValueError(f"target {target} has no mass on the rendered labels {list(labels)}")
return [v / total for v in vec]
def serialize_state(state: Any, compact: bool) -> Any:
"""Light template augmentation on the state serialization only.
qev.prompt.render_state pretty-prints non-string states with indent 2 and passes strings
through verbatim, so pre-serializing here with indent 2 is byte-identical to production and
the compact form is the only thing that varies. The question text is never touched.
"""
if isinstance(state, str) or state is None:
return state
if compact:
return json.dumps(state, ensure_ascii=False, separators=(",", ":"))
return json.dumps(state, ensure_ascii=False, indent=2)
@dataclass
class Example:
"""One rendered training or evaluation item."""
idx: int
prompt: str
kind: str
labels: list[str]
target: list[float]
source: str
task: str
suffix_start: int = -1
option_spans: list[tuple[int, int]] | None = None
PAD_FAMILIES = ("next_action",)
PAD_MAX_OPTIONS = 255
def pad_key(row: dict) -> str | None:
"""Rows that may be padded, and the pool they draw from. Tool-choice next_action rows (tau-style agents) only:
a tool of another domain is a real tool that is simply not the right next step here. Mind2Web elements, any row
with media (GUI screens, video) and edited_file files are left alone, because an element or file from another row
could exist in this state or would break the question's premise ("elements on the current page", "files the
agent has looked at")."""
q = row.get("question") or {}
src = str(row.get("source", ""))
if row.get("media"):
return None
if row.get("task") not in PAD_FAMILIES or q.get("type") != "choice" or src.startswith("retention") or "mind2web" in src:
return None
return f"{row['task']}:tools"
def build_option_pool(rows: Sequence[dict]) -> dict[str, list[tuple[str, Any]]]:
"""Every distinct option (name, description) of the paddable rows, per pad_key, for option padding."""
pool: dict[str, list[tuple[str, Any]]] = {}
seen: dict[str, set] = {}
for r in rows:
key = pad_key(r)
if key is None:
continue
names = seen.setdefault(key, set())
for name, desc in r["question"]["criteria"].items():
if name not in names:
names.add(name)
pool.setdefault(key, []).append((name, desc))
return pool
def pad_options(row: dict, pool: dict, prob: float, seed: int, char_budget: int = 24000,
state_char_cap: int = 30000) -> dict:
"""Option-count augmentation. With probability `prob`, a tool-choice row (pad_key) gets extra wrong options:
tools of other agent domains, up to a random total between 27 and 255 (in practice the pool holds 95 tools). The gold option and the target are unchanged. Rows with long states are left alone so the
padded prompt stays under max_len. Uses its own random stream, so unpadded rows render exactly as before."""
q = row["question"]
key = pad_key(row)
cands = pool.get(key) if key else None
if not cands:
return q
rng = random.Random(f"pad-{seed}")
if rng.random() >= prob:
return q
state = row.get("state")
state_chars = len(state) if isinstance(state, str) else len(json.dumps(state, ensure_ascii=False))
if state_chars > state_char_cap:
return q
crit = dict(q["criteria"])
k0 = len(crit)
target_k = rng.randint(max(k0 + 1, 27), PAD_MAX_OPTIONS)
budget = char_budget
for _ in range(4 * target_k):
if len(crit) >= target_k:
break
name, desc = cands[rng.randrange(len(cands))]
if name in crit:
continue
cost = len(name) + len(render_entry_text(desc)) + 8
if cost > budget:
break
crit[name] = desc
budget -= cost
if len(crit) <= k0:
return q
return {**q, "criteria": crit}
def render_entry_text(desc: Any) -> str:
return "" if desc is None else (desc if isinstance(desc, str) else json.dumps(desc, ensure_ascii=False))
def render_example(row: dict, tmpl, idx: int, seed: int | None = None, augment: bool = False,
option_pool: dict | None = None, pad_prob: float = 0.0) -> Example:
"""Render one row. `seed` drives the option permutation, the state serialization choice and (with an
option pool and pad_prob > 0) option padding; with seed None the frozen production rendering is used
(no permutation, no padding, indent 2)."""
qdict = row["question"]
if seed is not None and augment and option_pool and pad_prob > 0:
qdict = pad_options(row, option_pool, pad_prob, seed)
question = build_question(qdict)
base = render_question("q", question)
k = len(base.labels)
if seed is None:
rendered = base
compact = False
else:
rng = random.Random(seed)
order = list(range(k))
rng.shuffle(order)
rendered = render_question("q", question, order=order)
compact = augment and rng.random() < 0.5
state = serialize_state(row.get("state"), compact)
prompt = tmpl(state, rendered.suffix)
suffix_start = prompt.rindex(rendered.suffix)
spans = [(suffix_start + a, suffix_start + b) for a, b in rendered.option_spans or []]
return Example(
idx=idx,
prompt=prompt,
kind=rendered.kind,
labels=list(rendered.labels),
target=target_vector(row["target"], rendered.labels),
source=str(row.get("source", "unknown")),
task=str(row.get("task", "unknown")),
suffix_start=suffix_start,
option_spans=spans or None,
)
class _BlockImport:
"""Meta path finder that makes a package look uninstalled."""
def __init__(self, root: str) -> None:
self.root = root
def find_spec(self, fullname, path=None, target=None):
if fullname == self.root or fullname.startswith(self.root + "."):
raise ImportError(f"{self.root} is disabled by train.common.block_fla_kernels")
return None
def block_fla_kernels() -> None:
"""Force transformers onto its reference PyTorch gated delta rule instead of the fla kernel.
transformers resolves `chunk_gated_delta_rule` by importing `fla` at model-import time and
falls back to `torch_chunk_gated_delta_rule` when that import fails. fla 0.5.2 refuses to run
its gated backward kernel on H100/H200 with Triton in [3.4.0, 3.7.1) because the kernel produces
incorrect gradients there, so on such a box the fla path cannot be used for training at all.
The torch path is the correct reference implementation and is more than an order of magnitude
slower, so this is opt-in and never silent. Must be called before any model is loaded.
"""
import sys
for name in [m for m in sys.modules if m == "fla" or m.startswith("fla.")]:
del sys.modules[name]
try:
import transformers.utils.import_utils as import_utils
import_utils.is_flash_linear_attention_available = lambda *a, **k: False
except ImportError:
pass
if not any(isinstance(f, _BlockImport) and f.root == "fla" for f in sys.meta_path):
sys.meta_path.insert(0, _BlockImport("fla"))
log.warning("fla kernels disabled: gated delta rule layers will use the reference PyTorch "
"implementation, which is correct but more than an order of magnitude slower")
@dataclass
class Bundle:
model: Any
tokenizer: Any
config: Any
model_type: str
slot_ids: list[int]
template_kwargs: dict
processor: Any = None
counter: Any = None
readout: Any = None
@property
def multimodal(self) -> bool:
return self.processor is not None
def render_prompt(self, state: Any, suffix: str) -> str:
return self.tokenizer.apply_chat_template(
build_messages(state, suffix), tokenize=False, add_generation_prompt=True, **self.template_kwargs
)
def template_for(self, row: dict):
"""The prompt renderer for one row: the text template, or for a multimodal bundle the template that turns
the row's media placeholders into vision blocks (identical text for rows without media)."""
if not self.multimodal:
return self.render_prompt
from train import mm
media = row.get("media") or []
return lambda state, suffix: mm.render_prompt_mm(self.processor, self.template_kwargs, build_messages,
state, suffix, media)
def prompt_length(self, prompt: str, row: dict) -> int:
if not self.multimodal:
return len(self.encode(prompt))
return self.counter.length(prompt, row.get("media") or [])
def encode(self, text: str) -> list[int]:
return self.tokenizer.encode(text, add_special_tokens=False)
def verify_slots(tokenizer, model_path: str) -> list[int]:
"""Answer slots are the standalone label tokens (A..Z, then two-letter labels up to 256 slots), as qev.engine
verifies them. Training needs all of them."""
ids = []
for letter in SLOT_LABELS:
enc = tokenizer.encode(letter, add_special_tokens=False)
if len(enc) != 1 or tokenizer.decode(enc) != letter:
raise ValueError(f"answer slot {letter!r} is not a single round-trip token in {model_path}")
ids.append(enc[0])
if len(set(ids)) != len(ids):
raise ValueError("answer slot tokens collide")
return ids
def load_bundle(model_path: str, device: str = "cuda:0", dtype: str = "bfloat16", train: bool = False,
multimodal: bool = False, chat_template: str | None = None, load_model: bool = True) -> Bundle:
"""Load a causal LM the same way qev.engine does, including the Qwen3.5 special case. With multimodal=True the
vision model (Qwen3_5ForConditionalGeneration) and its processor are loaded instead of the text-only LM.
`chat_template` (a .jinja path) is only for base checkpoints that ship without one."""
import torch
import transformers
local = Path(model_path).exists()
common = {"local_files_only": local, "trust_remote_code": False}
config = transformers.AutoConfig.from_pretrained(model_path, **common)
processor = counter = None
if multimodal:
from train import mm
processor = transformers.AutoProcessor.from_pretrained(model_path, **common)
if chat_template:
processor.chat_template = Path(chat_template).read_text()
tokenizer = processor.tokenizer
if tokenizer.chat_template is None:
tokenizer.chat_template = processor.chat_template
cls = transformers.Qwen3_5ForConditionalGeneration if config.model_type == "qwen3_5" else \
transformers.AutoModelForImageTextToText
counter = mm.TokenCounter(processor)
else:
tokenizer = transformers.AutoTokenizer.from_pretrained(model_path, **common)
if chat_template:
tokenizer.chat_template = Path(chat_template).read_text()
cls = transformers.AutoModelForCausalLM
if config.model_type in {"qwen3_5", "qwen3_5_text"}:
cls = transformers.Qwen3_5ForCausalLM
config = config.get_text_config()
model = None
if load_model:
model = cls.from_pretrained(model_path, config=config, dtype=getattr(torch, dtype),
device_map={"": device}, low_cpu_mem_usage=True, **common)
model.train() if train else model.eval()
model_type = config.model_type
template_kwargs = {"enable_thinking": False} if "qwen" in model_type else {}
slot_ids = verify_slots(tokenizer, model_path)
if tokenizer.pad_token_id is None:
tokenizer.pad_token = tokenizer.eos_token
return Bundle(model=model, tokenizer=tokenizer, config=config, model_type=model_type,
slot_ids=slot_ids, template_kwargs=template_kwargs, processor=processor, counter=counter)
def linear_projection_modules(model) -> list[str]:
"""Every linear projection leaf, by full module path. Routing gates and the LM head stay frozen.
Full paths rather than short names on purpose: peft matches a short name against every module
whose path ends with it, and some models (gemma-4-E4B-it) give the same suffix to a wrapper
that is not an `nn.Linear` at all, which peft then refuses to adapt. Matching the exact paths
of the modules we checked avoids that.
"""
import torch
names: list[str] = []
for name, module in model.named_modules():
if type(module) is not torch.nn.Linear:
continue
if ".visual." in f".{name}." or name.startswith("visual"):
continue
short = name.split(".")[-1]
if short in {"lm_head", "router", "score", "classifier"}:
continue
if "proj" not in short:
continue
names.append(name)
return names
def short_names(paths: Sequence[str]) -> list[str]:
return sorted({p.split(".")[-1] for p in paths})
_TENSOR_KEEP = True
def readout_logits(model, input_ids, attention_mask, ends):
"""Full-vocabulary logits at each row's last real token, under RIGHT padding.
Right padding is what the readout wants: under causal attention a padded tail cannot reach
the readout position, so row i reads out at position ends[i] = len_i - 1 and the default
position_ids (arange) are already correct for every real token. Left padding would shift the
positions of the real tokens, which is why it is not used here.
We never materialise [B, T, V]. The primary path passes `logits_to_keep` as a tensor of the
distinct readout positions, exactly like qev.engine._run_batched. If a model rejects the
tensor form, we fall back to an integer tail width, which every implementation supports and
which is just as cheap because batches are length-sorted.
"""
import torch
global _TENSOR_KEEP
bsz, seqlen = input_ids.shape
ends = [int(e) for e in ends]
rows = torch.arange(bsz, device=input_ids.device)
if _TENSOR_KEEP:
keep = sorted(set(ends))
try:
ltk = torch.tensor(keep, dtype=torch.long, device=input_ids.device)
out = model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False,
return_dict=True, logits_to_keep=ltk)
pos = torch.tensor([keep.index(e) for e in ends], dtype=torch.long, device=input_ids.device)
return out.logits[rows, pos]
except Exception as exc:
_TENSOR_KEEP = False
log.warning("tensor logits_to_keep unavailable (%s); using integer tail width", exc)
width = seqlen - min(ends)
out = model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False,
return_dict=True, logits_to_keep=width)
pos = torch.tensor([e - (seqlen - width) for e in ends], dtype=torch.long, device=input_ids.device)
return out.logits[rows, pos]
def batch_scores(bundle: Bundle, model, examples: Sequence[Example], rows: Sequence[dict], device):
"""Option scores [B, Kmax] (-inf past each row's options) and their mask for a right-padded batch, under the
bundle's readout (qev.readout): causal or noncausal attention, slot_lm or head scoring. The same function scores
training steps, in-training evals and train.eval_mm, and qev.engine reproduces it for serving."""
import torch
from qev import readout as ro
rd = bundle.readout
cfg = rd.config if rd is not None else ro.ReadoutConfig()
ks = [len(ex.labels) for ex in examples]
if bundle.multimodal:
from train import mm
inputs, ends = mm.mm_inputs(bundle.processor, [ex.prompt for ex in examples],
[r.get("media") or [] for r in rows], device)
shifts = [bundle.counter.media_extra(r.get("media") or []) for r in rows]
else:
input_ids, attention_mask, ends = pad_batch([bundle.encode(ex.prompt) for ex in examples], bundle.tokenizer.pad_token_id, device)
inputs = {"input_ids": input_ids, "attention_mask": attention_mask}
shifts = [0] * len(examples)
ctx = ro.blocks(None)
spans = None
if cfg.needs_layout:
prefixes, spans = [], []
for ex, shift, end in zip(examples, shifts, ends):
ids, prefix, sp = ro.token_layout(bundle.tokenizer, ex.prompt, ex.suffix_start, ex.option_spans)
if len(ids) + shift != end + 1:
raise ValueError(f"layout of row {ex.idx} has {len(ids) + shift} tokens, the batch has {end + 1}")
if cfg.head and len(sp) != len(ex.labels):
raise ValueError(f"row {ex.idx}: {len(sp)} option spans for {len(ex.labels)} options")
prefixes.append(prefix + shift)
spans.append([(a + shift, b + shift) for a, b in sp])
if cfg.noncausal:
width = inputs["input_ids"].shape[1]
ctx = ro.blocks(ro.block_ids(prefixes, [e + 1 for e in ends], width, device))
with ctx:
if cfg.head:
out = model(**inputs, use_cache=False, return_dict=True, logits_to_keep=1)
hidden = rd.capture.pop()
kmax = max(ks)
rows_ix = torch.arange(len(examples), device=hidden.device)
h_ans = hidden[rows_ix, torch.tensor(ends, device=hidden.device)]
scores = rd.head(h_ans, ro.pool_options(hidden, spans, kmax))
# every FSDP unit (the LM head too) must take part in the backward
scores = scores + 0.0 * out.logits.float().sum()
mask = torch.zeros((len(ks), kmax), dtype=torch.bool, device=scores.device)
for i, k in enumerate(ks):
mask[i, :k] = True
return scores.masked_fill(~mask, float("-inf")), mask
if bundle.multimodal:
from train import mm
vocab_logits = mm.mm_readout_logits(model, inputs, ends)
else:
vocab_logits = readout_logits(model, inputs["input_ids"], inputs["attention_mask"], ends)
return slot_view(vocab_logits, bundle.slot_ids, ks)
def slot_view(vocab_logits, slot_ids, ks):
"""Gather the first K slot logits per row into a padded [B, Kmax] tensor plus a mask."""
import torch
bsz = vocab_logits.shape[0]
kmax = max(ks)
idx = torch.tensor(slot_ids[:kmax], dtype=torch.long, device=vocab_logits.device)
sel = vocab_logits.index_select(1, idx).float()
mask = torch.zeros((bsz, kmax), dtype=torch.bool, device=vocab_logits.device)
for i, k in enumerate(ks):
mask[i, :k] = True
sel = sel.masked_fill(~mask, float("-inf"))
return sel, mask
def pad_batch(id_lists: Sequence[Sequence[int]], pad_id: int, device):
"""Right padding. Returns input_ids, attention_mask and the readout index per row."""
import torch
width = max(len(x) for x in id_lists)
bsz = len(id_lists)
input_ids = torch.full((bsz, width), pad_id, dtype=torch.long, device=device)
attention_mask = torch.zeros((bsz, width), dtype=torch.long, device=device)
ends = []
for i, ids in enumerate(id_lists):
input_ids[i, : len(ids)] = torch.tensor(ids, dtype=torch.long, device=device)
attention_mask[i, : len(ids)] = 1
ends.append(len(ids) - 1)
return input_ids, attention_mask, ends
def length_bucket_batches(lengths: Sequence[int], batch_tokens: int, max_rows: int = 256,
shuffle_seed: int | None = None) -> list[list[int]]:
"""Sort by length, then cut batches so that rows * padded width stays under batch_tokens.
Sorting keeps padding waste small; the batch order is shuffled so the optimizer does not see
all the short examples first.
"""
order = sorted(range(len(lengths)), key=lambda i: lengths[i])
batches: list[list[int]] = []
cur: list[int] = []
cur_max = 0
for i in order:
width = max(cur_max, lengths[i])
if cur and ((len(cur) + 1) * width > batch_tokens or len(cur) + 1 > max_rows):
batches.append(cur)
cur, cur_max = [i], lengths[i]
else:
cur.append(i)
cur_max = width
if cur:
batches.append(cur)
if shuffle_seed is not None:
random.Random(shuffle_seed).shuffle(batches)
return batches
def chunked(items: Iterable, size: int):
buf = []
for it in items:
buf.append(it)
if len(buf) >= size:
yield buf
buf = []
if buf:
yield buf
CONFIG_ALIASES = {"train": "train_file"}
def load_yaml_config(path: str | Path) -> dict:
import yaml
with open(path, "r", encoding="utf-8") as fh:
data = yaml.safe_load(fh) or {}
out = {}
for k, v in data.items():
key = str(k).replace("-", "_")
out[CONFIG_ALIASES.get(key, key)] = v
return out
def apply_config(parser, path: str | Path) -> None:
"""Load a YAML config as argparse defaults. Unknown keys are an error, not a silent no-op."""
cfg = load_yaml_config(path)
known = {a.dest for a in parser._actions}
unknown = sorted(set(cfg) - known)
if unknown:
parser.error(f"unknown keys in {path}: {', '.join(unknown)}")
parser.set_defaults(**cfg)
def progress(done: int, total: int, prefix: str = "", width: int = 30) -> str:
frac = 0.0 if total <= 0 else done / total
filled = int(round(frac * width))
return f"{prefix}[{'#' * filled}{'.' * (width - filled)}] {done}/{total} ({100 * frac:.1f}%)"
def fmt(x: float) -> str:
return "nan" if x is None or math.isnan(x) else f"{x:.4f}"
@dataclass
class Scored:
kind: str
k: int
logits: list[float]
target: list[float]
source: str
task: str
labels: list[str]
idx: int = -1
def collect_slot_logits(bundle: Bundle, rows: Sequence[dict], max_len: int = 4096,
batch_tokens: int = 16384, max_rows: int = 64, device: str = "cuda:0",
report_every: int = 10, quiet: bool = False, sync_batches=None) -> list[Scored]:
"""Run the frozen production rendering (no permutation, indent 2) over every row and keep the
slot logits at the readout position. No gradients, no sampling.
`sync_batches` is for a sharded (FSDP) model, where every forward is collective: it maps this rank's
batch count to the count all ranks must run, and the rank pads with one-token forwards. It also swaps
inference_mode for no_grad, since FSDP keeps the gathered weights' storage for later training steps."""
import torch
texts, examples = [], []
for i, row in enumerate(rows):
ex = render_example(row, bundle.render_prompt, i, seed=None, augment=False)
examples.append(ex)
texts.append(ex.prompt)
lengths = []
for chunk in chunked(texts, 512):
enc = bundle.tokenizer(chunk, add_special_tokens=False)["input_ids"]
lengths.extend(len(x) for x in enc)
usable = [i for i in range(len(rows)) if lengths[i] <= max_len]
if len(usable) < len(rows) and not quiet:
log.warning("%d of %d rows exceed max-len %d and are skipped", len(rows) - len(usable), len(rows), max_len)
batches = length_bucket_batches([lengths[i] for i in usable], batch_tokens, max_rows, shuffle_seed=None)
batches = [[usable[j] for j in b] for b in batches]
out: list[Scored] = []
dev = torch.device(device)
pad_id = bundle.tokenizer.pad_token_id
done = 0
last_report = -1
n_total = sync_batches(len(batches)) if sync_batches is not None else len(batches)
grad_off = torch.no_grad() if sync_batches is not None else torch.inference_mode()
with grad_off:
for _ in range(n_total - len(batches)):
ids = torch.tensor([[pad_id]], dtype=torch.long, device=dev)
readout_logits(bundle.model, ids, torch.ones_like(ids), [0])
for bi, batch in enumerate(batches):
exs = [examples[i] for i in batch]
sel, _ = batch_scores(bundle, bundle.model, exs, [rows[ex.idx] for ex in exs], dev)
sel = sel.float().cpu().tolist()
for r, ex in enumerate(exs):
out.append(Scored(kind=ex.kind, k=len(ex.labels), logits=sel[r][: len(ex.labels)],
target=list(ex.target), source=ex.source, task=ex.task, labels=list(ex.labels),
idx=ex.idx))
done += len(exs)
pct = int(100 * done / max(len(usable), 1)) // 10
if pct != last_report and not quiet:
last_report = pct
print(progress(done, len(usable), prefix="score "), flush=True)
return out
def metrics(scored: Sequence["Scored"], temp_for) -> dict:
"""Accuracy, NLL, Brier and ECE for a group of scored rows under a temperature function."""
from qev.calibrate import brier as brier_fn
from qev.calibrate import ece as ece_fn
from qev.calibrate import nll as nll_fn
from qev.calibrate import softmax as softmax_fn
if not scored:
return {"n": 0}
accs, nlls, briers, confs = [], [], [], []
for s in scored:
p = softmax_fn(s.logits, temp_for(s.kind, s.k))
gold = max(range(len(s.target)), key=s.target.__getitem__)
pred = max(range(len(p)), key=p.__getitem__)
accs.append(1.0 if pred == gold else 0.0)
nlls.append(nll_fn(p, s.target))
briers.append(brier_fn(p, s.target))
confs.append(max(p))
return {
"n": len(scored),
"acc": sum(accs) / len(accs),
"nll": sum(nlls) / len(nlls),
"brier": sum(briers) / len(briers),
"ece": ece_fn(confs, accs),
}
def row_to_question(row: dict) -> dict:
prim = row.get("primitive") or ("choice" if len(row["options"]) != 2 or {o["id"] for o in row["options"]} != {"true", "false"} else "noul")
if prim == "noul":
desc = {o["id"]: o["description"] for o in row["options"]}
return {"type": "noul", "instructions": row["question"], "criteria": {"true": desc.get("true"), "false": desc.get("false")}}
if prim == "score":
levels = [o["description"] for o in sorted(row["options"], key=lambda o: int(o["id"]))]
levels = [l.split(": ", 1)[1] if l.lower().startswith("level ") and ": " in l else l for l in levels]
return {"type": "score", "instructions": row["question"], "criteria": levels}
return {"type": "choice", "instructions": row["question"], "criteria": {o["id"]: o["description"] for o in row["options"]}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Multimodal rows for training and in-training evaluation.
A row may carry `media`: images and pre-extracted video frames, referenced in the state by placeholders`<image:N>` / `<video:N>` (1-based, in order of appearance). The prompt is the frozen text prompt of qev.prompt witheach placeholder replaced by the model's vision block, so a row without media renders exactly like a text row.
Token lengths are exact without decoding pixels: text tokens of the rendered prompt (one pad token per media item)plus, per image, the grid the processor's own smart_resize gives for its (h, w), and per video a probe of theprocessor on blank frames of the same count, size and fps (cached). `check_lengths` compares this with the processoron real rows."""from __future__ import annotations
import functoolsimport jsonimport loggingimport osimport refrom pathlib import Pathfrom typing import Any, Sequence
log = logging.getLogger("train.mm")
PLACEHOLDER = re.compile(r"<(image|video):(\d+)>")MM_ROOT = Path(os.environ.get("QEV_MM_ROOT", "data/onejev"))
def set_root(root: str | Path) -> None: global MM_ROOT MM_ROOT = Path(root)
def content_parts(text: str, media: Sequence[dict]) -> list[dict]: """Split a user-turn text at the media placeholders into chat content parts.""" parts, pos, seen = [], 0, [] for m in PLACEHOLDER.finditer(text): if m.start() > pos: parts.append({"type": "text", "text": text[pos:m.start()]}) kind, n = m.group(1), int(m.group(2)) if n < 1 or n > len(media) or media[n - 1]["type"] != kind: raise ValueError(f"placeholder {m.group(0)} does not match media {n} of {len(media)}") parts.append({"type": kind}) seen.append(n) pos = m.end() if pos < len(text): parts.append({"type": "text", "text": text[pos:]}) if seen != list(range(1, len(media) + 1)): raise ValueError(f"media must be referenced once each, in order; saw {seen} for {len(media)} items") return parts
def render_prompt_mm(processor, template_kwargs, messages_fn, state: Any, suffix: str, media: Sequence[dict]) -> str: """Chat-rendered prompt with one vision block per media item (pads expanded later by the processor).""" msgs = messages_fn(state, suffix) user = msgs[-1]["content"] msgs = msgs[:-1] + [{"role": "user", "content": content_parts(user, media) if media else user}] return processor.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, **template_kwargs)
def load_media(media: Sequence[dict]): """PIL images, frame lists and video metadata, in media order.""" from PIL import Image from transformers.video_utils import VideoMetadata
images, videos, metas = [], [], [] for m in media: if m["type"] == "image": with Image.open(MM_ROOT / m["path"]) as im: images.append(im.convert("RGB")) else: frames = [] for p in m["frames"]: with Image.open(MM_ROOT / p) as im: frames.append(im.convert("RGB")) n = len(frames) fps = float(m.get("fps") or 1.0) videos.append(frames) metas.append(VideoMetadata(total_num_frames=n, fps=fps, frames_indices=list(range(n)), duration=n / fps)) return images, videos, metas
class TokenCounter: """Exact prompt length for a rendered prompt plus its media, without decoding any pixels."""
def __init__(self, processor): self.processor = processor self.tok = processor.tokenizer ip = processor.image_processor self.merge = ip.merge_size self.factor = ip.patch_size * ip.merge_size self.min_pixels = ip.size["shortest_edge"] self.max_pixels = ip.size["longest_edge"]
def image_tokens(self, h: int, w: int) -> int: from transformers.models.qwen2_vl.image_processing_qwen2_vl import smart_resize
hh, ww = smart_resize(h, w, factor=self.factor, min_pixels=self.min_pixels, max_pixels=self.max_pixels) return (hh // self.factor) * (ww // self.factor)
@functools.lru_cache(maxsize=4096) def video_extra(self, n: int, h: int, w: int, fps: float) -> int: """Tokens a video block adds beyond its single pad token, probed on blank frames (cached per shape).""" from PIL import Image from transformers.video_utils import VideoMetadata
frames = [Image.new("RGB", (w, h)) for _ in range(n)] base = "a<|vision_start|><|video_pad|><|vision_end|>b" md = VideoMetadata(total_num_frames=n, fps=fps, frames_indices=list(range(n)), duration=n / fps) out = self.processor(text=[base], videos=[frames], video_metadata=[md], videos_kwargs={"do_sample_frames": False, "cap_pixels_per_frame": True}) return len(out["input_ids"][0]) - len(self.tok(base, add_special_tokens=False)["input_ids"])
def media_extra(self, media: Sequence[dict]) -> int: """Tokens the media add beyond the single pad token each one has in the rendered prompt.""" n = 0 for m in media: if m["type"] == "image": n += self.image_tokens(int(m["h"]), int(m["w"])) - 1 else: n += self.video_extra(len(m["frames"]), int(m["h"]), int(m["w"]), float(m.get("fps") or 1.0)) return n
def length(self, prompt: str, media: Sequence[dict]) -> int: return len(self.tok(prompt, add_special_tokens=False)["input_ids"]) + self.media_extra(media)
def mm_inputs(processor, prompts: Sequence[str], medias: Sequence[Sequence[dict]], device): """Processor tensors for a right-padded batch, and the readout index per row.""" images, videos, metas = [], [], [] for media in medias: im, vi, md = load_media(media) images += im videos += vi metas += md kw = {} if images: kw["images"] = images if videos: kw["videos"] = videos kw["video_metadata"] = metas kw["videos_kwargs"] = {"do_sample_frames": False, "cap_pixels_per_frame": True} processor.tokenizer.padding_side = "right" out = processor(text=list(prompts), padding=True, return_tensors="pt", **kw) out = {k: v.to(device) for k, v in out.items()} ends = (out["attention_mask"].sum(dim=1) - 1).tolist() return out, ends
def mm_readout_logits(model, inputs: dict, ends: Sequence[int]): """Full-vocabulary logits at each row's last real token (right padding), like common.readout_logits.""" import torch
keep = sorted(set(int(e) for e in ends)) ltk = torch.tensor(keep, dtype=torch.long, device=inputs["input_ids"].device) out = model(**inputs, use_cache=False, return_dict=True, logits_to_keep=ltk) rows = torch.arange(len(ends), device=ltk.device) pos = torch.tensor([keep.index(int(e)) for e in ends], dtype=torch.long, device=ltk.device) return out.logits[rows, pos]
def check_lengths(bundle, rows: Sequence[dict], render, limit: int = 50) -> list[tuple[str, int, int]]: """(id, counted, processor) for rows whose counted length differs from the processor's. Loads real media.""" bad = [] for i, row in enumerate(rows[:limit]): prompt = render(row, i) media = row.get("media") or [] counted = bundle.counter.length(prompt, media) out, _ = mm_inputs(bundle.processor, [prompt], [media], "cpu") real = int(out["input_ids"].shape[1]) if counted != real: bad.append((row.get("id"), counted, real)) return bad1234567891011121314151617181920212223242526Copyright (c) 2015, Xinlei Chen, Hao Fang, Tsung-Yi Lin, and Ramakrishna Vedantam
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.12345678910111213141516171819Copyright (c) 2015 Xinlei Chen, Hao Fang, Tsung-Yi Lin, and Ramakrishna Vedantam
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.1__author__ = 'tylin'1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/usr/bin/env python
#
# File Name : bleu.py
#
# Description : Wrapper for BLEU scorer.
#
# Creation Date : 06-01-2015
# Last Modified : Thu 19 Mar 2015 09:13:28 PM PDT
# Authors : Hao Fang <hfang@uw.edu> and Tsung-Yi Lin <tl483@cornell.edu>
from .bleu_scorer import BleuScorer
class Bleu:
def __init__(self, n=4):
# default compute Blue score up to 4
self._n = n
self._hypo_for_image = {}
self.ref_for_image = {}
def compute_score(self, gts, res):
bleu_scorer = BleuScorer(n=self._n)
for i in range(len(res)):
hypo = res[i]
ref = gts[i]
# Sanity check.
assert(type(hypo) is list)
assert(len(hypo) == 1)
assert(type(ref) is list)
assert(len(ref) >= 1)
bleu_scorer += (hypo[0], ref)
#score, scores = bleu_scorer.compute_score(option='shortest')
score, scores = bleu_scorer.compute_score(option='closest', verbose=1)
#score, scores = bleu_scorer.compute_score(option='average', verbose=1)
# return (bleu, bleu_info)
return score, scores
def method(self):
return "Bleu"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263#!/usr/bin/env python
# bleu_scorer.py
# David Chiang <chiang@isi.edu>
# Copyright (c) 2004-2006 University of Maryland. All rights
# reserved. Do not redistribute without permission from the
# author. Not for commercial use.
# Modified by:
# Hao Fang <hfang@uw.edu>
# Tsung-Yi Lin <tl483@cornell.edu>
'''Provides:
cook_refs(refs, n=4): Transform a list of reference sentences as strings into a form usable by cook_test().
cook_test(test, refs, n=4): Transform a test sentence as a string (together with the cooked reference sentences) into a form usable by score_cooked().
'''
import copy
import sys, math, re
from collections import defaultdict
def precook(s, n=4, out=False):
"""Takes a string as input and returns an object that can be given to
either cook_refs or cook_test. This is optional: cook_refs and cook_test
can take string arguments as well."""
words = s.split()
counts = defaultdict(int)
for k in range(1,n+1):
for i in range(len(words)-k+1):
ngram = tuple(words[i:i+k])
counts[ngram] += 1
return (len(words), counts)
def cook_refs(refs, eff=None, n=4): ## lhuang: oracle will call with "average"
'''Takes a list of reference sentences for a single segment
and returns an object that encapsulates everything that BLEU
needs to know about them.'''
reflen = []
maxcounts = {}
for ref in refs:
rl, counts = precook(ref, n)
reflen.append(rl)
for (ngram,count) in counts.items():
maxcounts[ngram] = max(maxcounts.get(ngram,0), count)
# Calculate effective reference sentence length.
if eff == "shortest":
reflen = min(reflen)
elif eff == "average":
reflen = float(sum(reflen))/len(reflen)
## lhuang: N.B.: leave reflen computaiton to the very end!!
## lhuang: N.B.: in case of "closest", keep a list of reflens!! (bad design)
return (reflen, maxcounts)
def cook_test(test, xxx_todo_changeme, eff=None, n=4):
'''Takes a test sentence and returns an object that
encapsulates everything that BLEU needs to know about it.'''
(reflen, refmaxcounts) = xxx_todo_changeme
testlen, counts = precook(test, n, True)
result = {}
# Calculate effective reference sentence length.
if eff == "closest":
result["reflen"] = min((abs(l-testlen), l) for l in reflen)[1]
else: ## i.e., "average" or "shortest" or None
result["reflen"] = reflen
result["testlen"] = testlen
result["guess"] = [max(0,testlen-k+1) for k in range(1,n+1)]
result['correct'] = [0]*n
for (ngram, count) in counts.items():
result["correct"][len(ngram)-1] += min(refmaxcounts.get(ngram,0), count)
return result
class BleuScorer(object):
"""Bleu scorer.
"""
__slots__ = "n", "crefs", "ctest", "_score", "_ratio", "_testlen", "_reflen", "special_reflen"
# special_reflen is used in oracle (proportional effective ref len for a node).
def copy(self):
''' copy the refs.'''
new = BleuScorer(n=self.n)
new.ctest = copy.copy(self.ctest)
new.crefs = copy.copy(self.crefs)
new._score = None
return new
def __init__(self, test=None, refs=None, n=4, special_reflen=None):
''' singular instance '''
self.n = n
self.crefs = []
self.ctest = []
self.cook_append(test, refs)
self.special_reflen = special_reflen
def cook_append(self, test, refs):
'''called by constructor and __iadd__ to avoid creating new instances.'''
if refs is not None:
self.crefs.append(cook_refs(refs))
if test is not None:
cooked_test = cook_test(test, self.crefs[-1])
self.ctest.append(cooked_test) ## N.B.: -1
else:
self.ctest.append(None) # lens of crefs and ctest have to match
self._score = None ## need to recompute
def ratio(self, option=None):
self.compute_score(option=option)
return self._ratio
def score_ratio(self, option=None):
'''return (bleu, len_ratio) pair'''
return (self.fscore(option=option), self.ratio(option=option))
def score_ratio_str(self, option=None):
return "%.4f (%.2f)" % self.score_ratio(option)
def reflen(self, option=None):
self.compute_score(option=option)
return self._reflen
def testlen(self, option=None):
self.compute_score(option=option)
return self._testlen
def retest(self, new_test):
if type(new_test) is str:
new_test = [new_test]
assert len(new_test) == len(self.crefs), new_test
self.ctest = []
for t, rs in zip(new_test, self.crefs):
self.ctest.append(cook_test(t, rs))
self._score = None
return self
def rescore(self, new_test):
''' replace test(s) with new test(s), and returns the new score.'''
return self.retest(new_test).compute_score()
def size(self):
assert len(self.crefs) == len(self.ctest), "refs/test mismatch! %d<>%d" % (len(self.crefs), len(self.ctest))
return len(self.crefs)
def __iadd__(self, other):
'''add an instance (e.g., from another sentence).'''
if type(other) is tuple:
## avoid creating new BleuScorer instances
self.cook_append(other[0], other[1])
else:
assert self.compatible(other), "incompatible BLEUs."
self.ctest.extend(other.ctest)
self.crefs.extend(other.crefs)
self._score = None ## need to recompute
return self
def compatible(self, other):
return isinstance(other, BleuScorer) and self.n == other.n
def single_reflen(self, option="average"):
return self._single_reflen(self.crefs[0][0], option)
def _single_reflen(self, reflens, option=None, testlen=None):
if option == "shortest":
reflen = min(reflens)
elif option == "average":
reflen = float(sum(reflens))/len(reflens)
elif option == "closest":
reflen = min((abs(l-testlen), l) for l in reflens)[1]
else:
assert False, "unsupported reflen option %s" % option
return reflen
def recompute_score(self, option=None, verbose=0):
self._score = None
return self.compute_score(option, verbose)
def compute_score(self, option=None, verbose=0):
n = self.n
small = 1e-9
tiny = 1e-15 ## so that if guess is 0 still return 0
bleu_list = [[] for _ in range(n)]
if self._score is not None:
return self._score
if option is None:
option = "average" if len(self.crefs) == 1 else "closest"
self._testlen = 0
self._reflen = 0
totalcomps = {'testlen':0, 'reflen':0, 'guess':[0]*n, 'correct':[0]*n}
# for each sentence
for comps in self.ctest:
testlen = comps['testlen']
self._testlen += testlen
if self.special_reflen is None: ## need computation
reflen = self._single_reflen(comps['reflen'], option, testlen)
else:
reflen = self.special_reflen
self._reflen += reflen
for key in ['guess','correct']:
for k in range(n):
totalcomps[key][k] += comps[key][k]
# append per image bleu score
bleu = 1.
for k in range(n):
bleu *= (float(comps['correct'][k]) + tiny) \
/(float(comps['guess'][k]) + small)
bleu_list[k].append(bleu ** (1./(k+1)))
ratio = (testlen + tiny) / (reflen + small) ## N.B.: avoid zero division
if ratio < 1:
for k in range(n):
bleu_list[k][-1] *= math.exp(1 - 1/ratio)
# if verbose > 1:
# print(comps, reflen)
totalcomps['reflen'] = self._reflen
totalcomps['testlen'] = self._testlen
bleus = []
bleu = 1.
for k in range(n):
bleu *= float(totalcomps['correct'][k] + tiny) \
/ (totalcomps['guess'][k] + small)
bleus.append(bleu ** (1./(k+1)))
ratio = (self._testlen + tiny) / (self._reflen + small) ## N.B.: avoid zero division
if ratio < 1:
for k in range(n):
bleus[k] *= math.exp(1 - 1/ratio)
# if verbose > 0:
# print(totalcomps)
# print("ratio:", ratio)
self._score = bleus
return self._score, bleu_list1__author__ = 'tylin'.gitattributes+6
README.md+10-6
app.pyAdded+126
caption/beam.pyAdded+42
caption/cama_reference.pyAdded+46
caption/model.pyAdded+36
caption/runner.pyAdded+87
caption/visual.pyAdded+47
data/levir/config.jsonAdded+1
data/levir/vocab.jsonAdded+1
inference.pyAdded+98
judge/event_reward_v7.pyAdded+369
judge/legacy_event_parse.pyAdded+84
judge/qa_reward.pyAdded+465
judge/qa_reward_v2.pyAdded+116
judge/questions.pyAdded+83
judge/runner.pyAdded+52
judge/stage1_runtime.pyAdded+150
judge/stage2_runtime.pyAdded+158
pipeline.pyAdded+142
public/cases.jsonAdded+1
public/images/test_000033_A.pngAdded

Large File Pointer Details
- SHA256: 7f1ff6b14457251a0d609d0998401dd75b66e28926b09d1c282f1d5c354c95c5
- Pointer size: 131 Bytes
- Size of remote file: 157 kB
public/images/test_000033_B.pngAdded

Large File Pointer Details
- SHA256: 030fffd7ac6ac86f9aaceff8f76b0896b9c8fa5f652150f8c273aeb5e4788d59
- Pointer size: 131 Bytes
- Size of remote file: 136 kB
public/images/test_001095_A.pngAdded

Large File Pointer Details
- SHA256: 04991c6725de5675d153e0c8b3385570393412b5cb06109257d8fe8786fb8c15
- Pointer size: 131 Bytes
- Size of remote file: 112 kB
public/images/test_001095_B.pngAdded

public/images/test_001324_A.pngAdded

Large File Pointer Details
- SHA256: bec18fd1e7811d33ee9d9c3e9eeab425508120a45cc090d8e518eaf839b54392
- Pointer size: 131 Bytes
- Size of remote file: 107 kB
public/images/test_001324_B.pngAdded

public/images/test_001549_A.pngAdded

Large File Pointer Details
- SHA256: 6c08438281e690fbd4ac6f426a6bf5f80bb1a5af67bb150e2cc9eac2b8d30b18
- Pointer size: 131 Bytes
- Size of remote file: 156 kB
public/images/test_001549_B.pngAdded

Large File Pointer Details
- SHA256: 52fc361dea7d9cd9d99095be1b3d0e62bd4fc63186ec3661bc10898fe4767167
- Pointer size: 131 Bytes
- Size of remote file: 136 kB
requirements.txtAdded+19
vendor/NOTICE.mdAdded+5
vendor/OneJev/LICENSEAdded+202
vendor/OneJev/modeling_qwen3_5.py.referenceAdded+1971
vendor/OneJev/qev/__init__.pyAdded+4
vendor/OneJev/qev/answers.pyAdded+74
vendor/OneJev/qev/calibrate.pyAdded+114
vendor/OneJev/qev/client.pyAdded+114
vendor/OneJev/qev/prompt.pyAdded+168
vendor/OneJev/qev/readout.pyAdded+269
vendor/OneJev/qev/schema.pyAdded+118
vendor/OneJev/train/__init__.pyAdded+1
vendor/OneJev/train/common.pyAdded+676
vendor/OneJev/train/mm.pyAdded+172
vendor/metrics/LICENSEAdded+26
vendor/metrics/__init__.pyAdded
vendor/metrics/bleu/LICENSEAdded+19
vendor/metrics/bleu/__init__.pyAdded+1
vendor/metrics/bleu/bleu.pyAdded+44
vendor/metrics/bleu/bleu_scorer.pyAdded+263
vendor/metrics/cider/__init__.pyAdded+1