Implement the plan as specified, it is attached for your reference. Do NOT edit the plan file itself.
To-do's from the plan have already been created. Do not create them again. Mark them as in_progress as you work, starting with the first one. Don't stop until you have completed all the to-dos.
@outputs/baseline_v1 我已经完成了训练 Ensemble × MBR for Deep Past Challenge
Cross-model candidate pooling + chrF++ consensus selection
This notebook builds a submission pipeline for the Deep Past Challenge – Translate Akkadian to English competition.
Method summary
Model A: byt5-akkadian-optimized-34x
Model B: byt5-akkadian-mbr-v2
Each model generates:
beam-search candidates
stochastic sampling candidates
Candidate pools are merged across models
Final output is selected by Minimum Bayes Risk (MBR) using chrF++
Main design choices
Cross-model diversity to reduce shared failure modes
Preprocessing rules adapted from the stronger MBR-oriented pipeline
BF16 autocast for safer mixed precision on ByT5
Conservative postprocessing that preserves / when needed
Huge thanks to @mattiaangeli and @assiaben for their pre-trained models
Imports and runtime setup
This section loads all required libraries and sets a few runtime defaults for Kaggle.
import os
import gc
import re
import json
import math
import random
import logging
import warnings
from pathlib import Path
from dataclasses import dataclass
from contextlib import nullcontext
from typing import List, Tuple
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader, Sampler
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from tqdm.auto import tqdm
import sacrebleu
warnings.filterwarnings("ignore")
os.environ.setdefault("OMP_NUM_THREADS", "4")
os.environ.setdefault("MKL_NUM_THREADS", "4")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "true")
'true'
2. BF16 utility helpers
These helpers detect whether BF16 autocast is available and create the proper context manager.
def _cuda_bf16_supported() -> bool:
if not torch.cuda.is_available():
return False
try:
return bool(getattr(torch.cuda, "is_bf16_supported", lambda: False)())
except Exception:
return False
def _bf16_ctx(device: torch.device, enabled: bool):
if enabled and device.type == "cuda" and _cuda_bf16_supported():
return torch.autocast(device_type="cuda", dtype=torch.bfloat16)
return nullcontext()
3. Configuration
All main generation, batching, postprocessing, and checkpointing options are collected here.
/usr/lib/python3.12/importlib/_bootstrap.py in _gcd_import(name, package, level)
/usr/lib/python3.12/importlib/_bootstrap.py in find_and_load(name, import)
/usr/lib/python3.12/importlib/_bootstrap.py in find_and_load_unlocked(name, import)
/usr/lib/python3.12/importlib/_bootstrap.py in _load_unlocked(spec)
/usr/lib/python3.12/importlib/_bootstrap_external.py in exec_module(self, module)
/usr/lib/python3.12/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)
/usr/local/lib/python3.12/dist-packages/transformers/models/t5/modeling_t5.py in
39 )
---> 40 from ...modeling_utils import PreTrainedModel
41 from ...pytorch_utils import ALL_LAYERNORM_LAYERS, find_pruneable_heads_and_indices, prune_linear_layer
/usr/local/lib/python3.12/dist-packages/transformers/modeling_utils.py in
47 from .integrations import PeftAdapterMixin, deepspeed_config, is_deepspeed_zero3_enabled
---> 48 from .loss.loss_utils import LOSS_MAPPING
49 from .pytorch_utils import ( # noqa: F401
/usr/local/lib/python3.12/dist-packages/transformers/loss/loss_utils.py in
18
---> 19 from .loss_deformable_detr import DeformableDetrForObjectDetectionLoss, DeformableDetrForSegmentationLoss
20 from .loss_for_object_detection import ForObjectDetectionLoss, ForSegmentationLoss
/usr/local/lib/python3.12/dist-packages/transformers/loss/loss_deformable_detr.py in
3
----> 4 from ..image_transforms import center_to_corners_format
5 from ..utils import is_scipy_available
/usr/local/lib/python3.12/dist-packages/transformers/image_transforms.py in
21
---> 22 from .image_utils import (
23 ChannelDimension,
/usr/local/lib/python3.12/dist-packages/transformers/image_utils.py in
57 if is_torchvision_available():
---> 58 from torchvision.transforms import InterpolationMode
59
/usr/local/lib/python3.12/dist-packages/torchvision/init.py in
9 from .extension import _HAS_OPS # usort:skip
---> 10 from torchvision import _meta_registrations, datasets, io, models, ops, transforms, utils # usort:skip
11
/usr/local/lib/python3.12/dist-packages/transformers/generation/utils.py in generate(self, inputs, generation_config, logits_processor, stopping_criteria, prefix_allowed_tokens_fn, synced_gpus, assistant_model, streamer, negative_prompt_ids, negative_prompt_attention_mask, **kwargs)
1991
1992 device = inputs_tensor.device
-> 1993 self._prepare_special_tokens(generation_config, kwargs_has_attention_mask, device=device)
1994
1995 # decoder-only models must use left-padding for batched generation.
/usr/local/lib/python3.12/dist-packages/transformers/generation/utils.py in _prepare_special_tokens(self, generation_config, kwargs_has_attention_mask, device)
1840 if (
1841 eos_token_tensor is not None
-> 1842 and isin_mps_friendly(elements=eos_token_tensor, test_elements=pad_token_tensor).any()
1843 ):
1844 if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:
/usr/local/lib/python3.12/dist-packages/transformers/pytorch_utils.py in isin_mps_friendly(elements, test_elements)
329 else:
330 # Note: don't use named arguments in torch.isin, see https://github.com/pytorch/pytorch/issues/126045
--> 331 return torch.isin(elements, test_elements)
AcceleratorError: CUDA error: no kernel image is available for execution on the device
Search for cudaErrorNoKernelImageForDevice' in https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__TYPES.html for more information. CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile with TORCH_USE_CUDA_DSA` to enable device-side assertions.
def _canon_decimal(x: float) -> str:
ip = int(math.floor(x + 1e-12))
frac = x - ip
best = min(_ALLOWED_FRACS, key=lambda t: abs(frac - t[0]))
code
if abs(frac - best[0]) <= _FRAC_TOL:
dec = best[1]
if ip == 0:
return dec
return f"{ip}{dec[1:]}" if dec.startswith("0.") else f"{ip}+{dec}"
return f"{x:.5f}".rstrip("0").rstrip(".")
class OptimizedPreprocessor:
def preprocess_batch(self, texts: List[str]) -> List[str]:
ser = pd.Series(texts).fillna("").astype(str)
ser = ser.apply(_ascii_to_diacritics)
code
# Uppercase determinatives are unwrapped, lowercase ones are converted to braces.
ser = ser.str.replace(_DET_UPPER_RE, r"\1", regex=True)
ser = ser.str.replace(_DET_LOWER_RE, r"{\1}", regex=True)
ser = _normalize_gaps_vec(ser)
ser = ser.str.translate(_CHAR_TRANS)
ser = ser.str.replace(_SUB_X, "", regex=False)
ser = ser.str.replace(_KUBABBAR_RE, "KÙ.BABBAR", regex=True)
ser = ser.str.replace(_EXACT_FRAC_RE, _frac_repl, regex=True)
ser = ser.str.replace(_FLOAT_RE, lambda m: _canon_decimal(float(m.group(1))), regex=True)
ser = ser.str.replace(_WS_RE, " ", regex=True).str.strip()
return ser.tolist()
6. Postprocessing rules
This block standardizes model outputs before MBR selection.
Included transformations
Gap unification
PN handling
Commodity-specific normalization
Shekel fraction normalization
Grammar-marker removal
Month normalization
Cleanup of repeated fragments and whitespace
_SOFT_GRAM_RE = re.compile(
r"(\s*(?:fem|plur|pl|sing|singular|plural|?|!)"
r"(?:.\s*(?:plur|plural|sing|singular))?"
r".?\s*[^)])", re.I
)
_BARE_GRAM_RE = re.compile(r"(?<!\w)(?:fem|sing|pl|plural).?(?!\w)\s", re.I)
_UNCERTAIN_RE = re.compile(r"(?)")
_CURLY_QUOTES_RE = re.compile("[\u201c\u201d\u2018\u2019]")
class VectorizedPostprocessor:
def postprocess_batch(self, translations: List[str]) -> List[str]:
s = pd.Series(translations).fillna("").astype(str)
code
s = _normalize_gaps_vec(s)
s = s.str.replace(_PN_RE, "<gap>", regex=True)
s = s.str.replace(_COMMODITY_RE, _commodity_repl, regex=True)
for pat, repl in _SHEKEL_REPLS:
s = s.str.replace(pat, repl, regex=True)
s = s.str.replace(_EXACT_FRAC_RE, _frac_repl, regex=True)
s = s.str.replace(_FLOAT_RE, lambda m: _canon_decimal(float(m.group(1))), regex=True)
s = s.str.replace(_SOFT_GRAM_RE, " ", regex=True)
s = s.str.replace(_BARE_GRAM_RE, " ", regex=True)
s = s.str.replace(_UNCERTAIN_RE, "", regex=True)
s = s.str.replace(_STRAY_MARKS_RE, "", regex=True)
s = s.str.replace(_SLASH_ALT_RE, "", regex=True)
# Remove only curly quotes; keep straight quotes and apostrophes.
s = s.str.replace(_CURLY_QUOTES_RE, "", regex=True)
s = s.str.replace(_MONTH_RE, _month_repl, regex=True)
s = s.str.replace(_MULTI_GAP_RE, "<gap>", regex=True)
s = s.str.replace("<gap>", "\x00GAP\x00", regex=False)
s = s.str.translate(_FORBIDDEN_TRANS)
s = s.str.replace("\x00GAP\x00", " <gap> ", regex=False)
s = s.str.replace(_REPEAT_WORD_RE, r"\1", regex=True)
for n in range(4, 1, -1):
pat = r"\b((?:\w+\s+){" + str(n-1) + r"}\w+)(?:\s+\1\b)+"
s = s.str.replace(pat, r"\1", regex=True)
s = s.str.replace(_PUNCT_SPACE_RE, r"\1", regex=True)
s = s.str.replace(_REPEAT_PUNCT_RE, r"\1", regex=True)
s = s.str.replace(_WS_RE, " ", regex=True).str.strip()
return s.tolist()
7. Dataset and bucketed batching
The dataset applies preprocessing once. The custom sampler groups similar sequence lengths together to reduce padding waste.
class AkkadianDataset(Dataset):
def init(self, df: pd.DataFrame, preprocessor: OptimizedPreprocessor, logger: logging.Logger):
self.sample_ids = df["id"].tolist()
proc = preprocessor.preprocess_batch(df["transliteration"].tolist())
self.input_texts = ["translate Akkadian to English: " + t for t in proc]
logger.info(f"Dataset: {len(self.sample_ids)} samples")
lengths = [len(t.split()) for _, t in dataset]
sorted_idx = sorted(range(len(lengths)), key=lambda i: lengths[i])
bsize = max(1, len(sorted_idx) // max(1, num_buckets))
self.buckets = [
sorted_idx[i * bsize : None if i == num_buckets - 1 else (i + 1) * bsize]
for i in range(num_buckets)
]
for i, b in enumerate(self.buckets):
if b:
bl = [lengths[x] for x in b]
logger.info(f" Bucket {i}: {len(b)} samples, len [{min(bl)}, {max(bl)}]")
def __iter__(self):
for bucket in self.buckets:
b = list(bucket)
if self.shuffle:
random.shuffle(b)
for i in range(0, len(b), self.batch_size):
yield b[i:i+self.batch_size]
def __len__(self):
return sum(math.ceil(len(b) / self.batch_size) for b in self.buckets)
logger.info(f"[{label}] Loading from {model_path}")
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
self.model = AutoModelForSeq2SeqLM.from_pretrained(model_path).to(cfg.device).eval()
if cfg.device.type == "cuda":
try:
torch.set_float32_matmul_precision("high")
except Exception:
pass
n = sum(p.numel() for p in self.model.parameters())
logger.info(f"[{label}] {n:,} parameters")
if cfg.device.type == "cuda":
used = torch.cuda.memory_allocated() / 1e9
logger.info(f"[{label}] GPU mem used: {used:.2f} GB")
if cfg.use_better_transformer and cfg.device.type == "cuda":
try:
from optimum.bettertransformer import BetterTransformer
self.model = BetterTransformer.transform(self.model)
logger.info(f"[{label}] BetterTransformer applied")
except Exception as e:
logger.warning(f"[{label}] BetterTransformer skipped: {e}")
def collate(self, batch_samples):
ids = [s[0] for s in batch_samples]
texts = [s[1] for s in batch_samples]
enc = self.tokenizer(
texts,
max_length=self.cfg.max_input_length,
padding=True,
truncation=True,
return_tensors="pt",
)
return ids, enc
def generate_candidates(self, input_ids, attention_mask, beam_size: int) -> List[List[str]]:
cfg = self.cfg
B = input_ids.shape[0]
ctx = _bf16_ctx(cfg.device, cfg.use_bf16_amp)
with ctx:
nb = max(beam_size, cfg.num_beam_cands)
beam_out = self.model.generate(
input_ids=input_ids,
attention_mask=attention_mask,
do_sample=False,
num_beams=nb,
num_return_sequences=cfg.num_beam_cands,
max_new_tokens=cfg.max_new_tokens,
length_penalty=cfg.length_penalty,
early_stopping=cfg.early_stopping,
repetition_penalty=cfg.repetition_penalty,
use_cache=True,
)
beam_texts = self.tokenizer.batch_decode(beam_out, skip_special_tokens=True)
samp_texts = []
if cfg.num_sample_cands > 0:
samp_out = self.model.generate(
input_ids=input_ids,
attention_mask=attention_mask,
do_sample=True,
num_beams=1,
top_p=cfg.mbr_top_p,
temperature=cfg.mbr_temperature,
num_return_sequences=cfg.num_sample_cands,
max_new_tokens=cfg.max_new_tokens,
repetition_penalty=cfg.repetition_penalty,
use_cache=True,
)
samp_texts = self.tokenizer.batch_decode(samp_out, skip_special_tokens=True)
Rb, Rs = cfg.num_beam_cands, cfg.num_sample_cands
pools = []
for i in range(B):
p = list(beam_texts[i*Rb:(i+1)*Rb])
if Rs > 0:
p += list(samp_texts[i*Rs:(i+1)*Rs])
pools.append(p)
return pools
def unload(self):
label = self.label
try:
from optimum.bettertransformer import BetterTransformer
self.model = BetterTransformer.reverse(self.model)
except Exception:
pass
del self.model
del self.tokenizer
self.model = None
self.tokenizer = None
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
free = (torch.cuda.get_device_properties(0).total_memory - torch.cuda.memory_allocated()) / 1e9
self.logger.info(f"[{label}] Unloaded. GPU free: {free:.2f} GB")
9. MBR selector
MBR chooses the candidate with the highest average chrF++ agreement against the other candidates in the pool.
class MBRSelector:
def init(self, pool_cap: int = 32):
self._metric = sacrebleu.metrics.CHRF(word_order=2)
self.pool_cap = pool_cap
code
def _chrfpp(self, a: str, b: str) -> float:
a, b = (a or "").strip(), (b or "").strip()
if not a or not b:
return 0.0
return float(self._metric.sentence_score(a, [b]).score)
@staticmethod
def _dedup(xs: List[str]) -> List[str]:
seen, out = set(), []
for x in xs:
x = str(x).strip()
if x and x not in seen:
out.append(x)
seen.add(x)
return out
def pick(self, candidates: List[str]) -> str:
cands = self._dedup(candidates)
if self.pool_cap:
cands = cands[:self.pool_cap]
n = len(cands)
if n == 0:
return ""
if n == 1:
return cands[0]
best_i, best_s = 0, -1e9
for i in range(n):
s = sum(self._chrfpp(cands[i], cands[j]) for j in range(n) if j != i)
s /= max(1, n - 1)
if s > best_s:
best_s, best_i = s, i
return cands[best_i]
10. End-to-end ensemble engine
This class runs the full pipeline:
preprocess test inputs
generate candidates with Model A
generate candidates with Model B
merge candidate pools
postprocess outputs
select the final translation with MBR
write checkpoints and validate the submission
class EnsembleMBREngine:
def init(self, cfg: EnsembleMBRConfig, logger: logging.Logger):
self.cfg = cfg
self.logger = logger
self.preprocessor = OptimizedPreprocessor()
self.postprocessor = VectorizedPostprocessor()
self.mbr = MBRSelector(pool_cap=cfg.mbr_pool_cap)
code
def _adaptive_beams(self, attn: torch.Tensor) -> int:
if not self.cfg.use_adaptive_beams:
return self.cfg.num_beams
med = float(attn.sum(dim=1).float().median().item())
short = max(self.cfg.num_beam_cands, self.cfg.num_beams // 2)
return short if med < 100 else self.cfg.num_beams
def _build_dataloader(self, dataset: AkkadianDataset, wrapper: ModelWrapper) -> DataLoader:
if self.cfg.use_bucket_batching:
sampler = BucketBatchSampler(
dataset,
self.cfg.batch_size,
self.cfg.num_buckets,
self.logger,
)
return DataLoader(
dataset,
batch_sampler=sampler,
num_workers=self.cfg.num_workers,
collate_fn=wrapper.collate,
pin_memory=(self.cfg.device.type == "cuda"),
)
return DataLoader(
dataset,
batch_size=self.cfg.batch_size,
shuffle=False,
num_workers=self.cfg.num_workers,
collate_fn=wrapper.collate,
pin_memory=(self.cfg.device.type == "cuda"),
)
def _run_one_model(self, wrapper: ModelWrapper, dataset: AkkadianDataset) -> dict:
dl = self._build_dataloader(dataset, wrapper)
pools_by_id = {}
with torch.inference_mode():
for batch_ids, enc in tqdm(dl, desc=f"[{wrapper.label}]"):
input_ids = enc.input_ids.to(self.cfg.device, non_blocking=True)
attn = enc.attention_mask.to(self.cfg.device, non_blocking=True)
beam_size = self._adaptive_beams(attn)
try:
batch_pools = wrapper.generate_candidates(input_ids, attn, beam_size)
for sid, pool in zip(batch_ids, batch_pools):
pools_by_id[str(sid)] = pool
except RuntimeError as e:
if "out of memory" in str(e).lower():
self.logger.error(f"OOM in [{wrapper.label}] — skipping batch")
torch.cuda.empty_cache()
for sid in batch_ids:
pools_by_id.setdefault(str(sid), [])
else:
raise
except Exception as e:
self.logger.error(f"[{wrapper.label}] batch error: {e}")
for sid in batch_ids:
pools_by_id.setdefault(str(sid), [])
if torch.cuda.is_available():
torch.cuda.empty_cache()
return pools_by_id
def run(self, test_df: pd.DataFrame) -> pd.DataFrame:
cfg, logger = self.cfg, self.logger
logger.info("=" * 60)
logger.info("Ensemble × MBR | Cross-model candidate pooling")
logger.info(f" Model A : {cfg.model_a_path}")
logger.info(f" Model B : {cfg.model_b_path}")
logger.info(f" Pool per model: beam×{cfg.num_beam_cands} + sample×{cfg.num_sample_cands}")
logger.info(f" MBR pool cap : {cfg.mbr_pool_cap}")
logger.info(f" BF16 AMP : {cfg.use_bf16_amp}")
logger.info(f" batch_size : {cfg.batch_size}")
logger.info("=" * 60)
dataset = AkkadianDataset(test_df, self.preprocessor, logger)
sample_ids = [str(s) for s in dataset.sample_ids]
logger.info("Phase 1/2 — Model A inference")
wrapper_a = ModelWrapper(cfg.model_a_path, cfg, logger, "Model-A")
pools_a = self._run_one_model(wrapper_a, dataset)
wrapper_a.unload()
del wrapper_a
logger.info("Phase 2/2 — Model B inference")
wrapper_b = ModelWrapper(cfg.model_b_path, cfg, logger, "Model-B")
pools_b = self._run_one_model(wrapper_b, dataset)
wrapper_b.unload()
del wrapper_b
logger.info("Phase 3/3 — Pool merge + MBR selection")
results: List[Tuple[str, str]] = []
for sid in tqdm(sample_ids, desc="MBR"):
combined = pools_a.get(sid, []) + pools_b.get(sid, [])
pp = self.postprocessor.postprocess_batch(combined) if combined else []
chosen = self.mbr.pick(pp)
if not chosen or not chosen.strip():
chosen = "The tablet is too damaged to translate."
results.append((sid, chosen))
if len(results) % cfg.checkpoint_freq == 0:
ckpt = Path(cfg.output_dir) / f"checkpoint_{len(results)}.csv"
pd.DataFrame(results, columns=["id", "translation"]).to_csv(ckpt, index=False)
logger.info(f" Checkpoint: {len(results)} rows → {ckpt}")
result_df = pd.DataFrame(results, columns=["id", "translation"])
self._validate(result_df)
return result_df
def _validate(self, df: pd.DataFrame):
logger = self.logger
logger.info("=" * 60)
empty = df["translation"].str.strip().eq("").sum()
lens = df["translation"].str.len()
logger.info(f"Empty : {empty} ({100 * empty / max(1, len(df)):.2f}%)")
logger.info(
f"Len mean : {lens.mean():.1f} median: {lens.median():.1f} min: {lens.min()} max: {lens.max()}"
)
for idx in [0, len(df)//4, len(df)//2, 3*len(df)//4, len(df)-1]:
row = df.iloc[idx]
logger.info(f" ID {row['id']}: {str(row['translation'])[:80]}")
logger.info("=" * 60)
11. Runtime summary helper
This small helper prints the environment before inference starts.
with open(Path(cfg.output_dir) / "ensemble_mbr_config.json", "w") as f:
json.dump(cfg_snap, f, indent=2)
print("\n" + "=" * 60)
print("Ensemble × MBR complete")
print(f"Submission : {out_path}")
print(f"Total rows : {len(results_df)}")
print("=" * 60)
2026-03-07 13:47:21,109 | INFO | Loading test data: /kaggle/input/deep-past-initiative-machine-translation/test.csv
2026-03-07 13:47:21,122 | INFO | Test samples: 4
2026-03-07 13:47:21,123 | INFO | ============================================================
2026-03-07 13:47:21,124 | INFO | Ensemble × MBR | Cross-model candidate pooling
2026-03-07 13:47:21,124 | INFO | Model A : /kaggle/input/final-byt5/byt5-akkadian-optimized-34x
2026-03-07 13:47:21,125 | INFO | Model B : /kaggle/input/models/mattiaangeli/byt5-akkadian-mbr-v2/pytorch/default/1
2026-03-07 13:47:21,127 | INFO | Pool per model: beam×4 + sample×2
2026-03-07 13:47:21,127 | INFO | MBR pool cap : 32
2026-03-07 13:47:21,128 | INFO | BF16 AMP : True
2026-03-07 13:47:21,128 | INFO | batch_size : 2
2026-03-07 13:47:21,129 | INFO | ============================================================
2026-03-07 13:47:21,134 | INFO | Dataset: 4 samples
2026-03-07 13:47:21,135 | INFO | Phase 1/2 — Model A inference
2026-03-07 13:47:21,135 | INFO | [Model-A] Loading from /kaggle/input/final-byt5/byt5-akkadian-optimized-34x
PyTorch : 2.8.0+cu126
CUDA : True
GPU : Tesla P100-PCIE-16GB
GPU Mem : 17.06 GB
BF16 : True
BF16 AMP : True
2026-03-07 13:47:23.572734: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
E0000 00:00:1772891243.766673 35 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
E0000 00:00:1772891243.818085 35 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
W0000 00:00:1772891244.324531 35 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.
W0000 00:00:1772891244.324578 35 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.
W0000 00:00:1772891244.324582 35 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.
W0000 00:00:1772891244.324584 35 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.
2026-03-07 13:47:57,789 | INFO | [Model-A] 581,653,248 parameters
2026-03-07 13:47:57,791 | INFO | [Model-A] GPU mem used: 2.38 GB
2026-03-07 13:47:57,793 | WARNING | [Model-A] BetterTransformer skipped: No module named 'optimum.bettertransformer'
2026-03-07 13:47:57,794 | INFO | Bucket 0: 1 samples, len [20, 20]
2026-03-07 13:47:57,794 | INFO | Bucket 1: 1 samples, len [20, 20]
2026-03-07 13:47:57,795 | INFO | Bucket 2: 1 samples, len [23, 23]
2026-03-07 13:47:57,795 | INFO | Bucket 3: 1 samples, len [38, 38]
2026-03-07 13:48:45,695 | INFO | [Model-A] Unloaded. GPU free: 17.05 GB
2026-03-07 13:48:45,696 | INFO | Phase 2/2 — Model B inference
2026-03-07 13:48:45,697 | INFO | [Model-B] Loading from /kaggle/input/models/mattiaangeli/byt5-akkadian-mbr-v2/pytorch/default/1
2026-03-07 13:49:04,251 | INFO | [Model-B] 581,653,248 parameters
2026-03-07 13:49:04,253 | INFO | [Model-B] GPU mem used: 2.39 GB
2026-03-07 13:49:04,254 | WARNING | [Model-B] BetterTransformer skipped: No module named 'optimum.bettertransformer'
2026-03-07 13:49:04,255 | INFO | Bucket 0: 1 samples, len [20, 20]
2026-03-07 13:49:04,255 | INFO | Bucket 1: 1 samples, len [20, 20]
2026-03-07 13:49:04,256 | INFO | Bucket 2: 1 samples, len [23, 23]
2026-03-07 13:49:04,257 | INFO | Bucket 3: 1 samples, len [38, 38]
2026-03-07 13:49:48,219 | INFO | [Model-B] Unloaded. GPU free: 17.05 GB
2026-03-07 13:49:48,220 | INFO | Phase 3/3 — Pool merge + MBR selection
2026-03-07 13:49:48,543 | INFO | ============================================================
2026-03-07 13:49:48,545 | INFO | Empty : 0 (0.00%)
2026-03-07 13:49:48,546 | INFO | Len mean : 192.8 median: 194.5 min: 134 max: 248
2026-03-07 13:49:48,548 | INFO | ID 0: Thus kārum Kanesh, say to the dātum, our messenger, every single colony an
2026-03-07 13:49:48,548 | INFO | ID 1: As for the tablet of the City, you are writing to the City. This day, whoever ac
2026-03-07 13:49:48,549 | INFO | ID 2: As soon as you have heard our letter, whether he has sold anything there for any
2026-03-07 13:49:48,550 | INFO | ID 3: I sent it to every single colony and the trading stations to every single colony
2026-03-07 13:49:48,551 | INFO | ID 3: I sent it to every single colony and the trading stations to every single colony
2026-03-07 13:49:48,552 | INFO | ============================================================
2026-03-07 13:49:48,560 | INFO | Saved → /kaggle/working/submission.csv (4 rows)
Notes for Kaggle submission
Make sure both model paths are attached as Kaggle datasets/models.
If optimum is unavailable, the notebook will still run normally.
For the full test set, you may want to tune:
batch_size
num_sample_cands
max_new_tokens
mbr_pool_cap 我正在计划写可以在kaggle上提交的笔记本(只不过我们是单模型) 看一看这个笔记本 我们要完全copy 其逻辑 只是改成单模型 可以更优秀的解码实践和推理实践 不要cell 只要一个py 和我讲讲你的方案
/usr/local/lib/python3.12/dist-packages/transformers/models/auto/auto_factory.py in _get_model_class(config, model_mapping)
386
387 def _get_model_class(config, model_mapping):
--> 388 supported_models = model_mapping[type(config)]
389 if not isinstance(supported_models, (list, tuple)):
390 return supported_models
/usr/local/lib/python3.12/dist-packages/transformers/models/auto/auto_factory.py in getitem(self, key)
761 if model_type in self._model_mapping:
762 model_name = self._model_mapping[model_type]
--> 763 return self._load_attr_from_module(model_type, model_name)
764
765 # Maybe there was several model types associated with this config.
/usr/local/lib/python3.12/dist-packages/transformers/models/auto/auto_factory.py in _load_attr_from_module(self, model_type, attr)
775 if module_name not in self._modules:
776 self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models")
--> 777 return getattribute_from_module(self._modules[module_name], attr)
778
779 def keys(self):
/usr/local/lib/python3.12/dist-packages/transformers/models/auto/auto_factory.py in getattribute_from_module(module, attr)
691 if isinstance(attr, tuple):
692 return tuple(getattribute_from_module(module, a) for a in attr)
--> 693 if hasattr(module, attr):
694 return getattr(module, attr)
695 # Some of the mappings have entries model_type -> object of another model type. In that case we try to grab the
/usr/local/lib/python3.12/dist-packages/transformers/utils/import_utils.py in getattr(self, name)
1764 value = Placeholder
1765 elif name in self._class_to_module.keys():
-> 1766 module = self._get_module(self._class_to_module[name])
1767 value = getattr(module, name)
1768 elif name in self._modules:
/usr/local/lib/python3.12/dist-packages/transformers/utils/import_utils.py in _get_module(self, module_name)
1778 return importlib.import_module("." + module_name, self.name)
1779 except Exception as e:
-> 1780 raise RuntimeError(
1781 f"Failed to import {self.name}.{module_name} because of the following error (look up to see its"
1782 f" traceback):\n{e}"
RuntimeError: Failed to import transformers.models.t5.modeling_t5 because of the following error (look up to see its traceback):
operator torchvision::nms does not exist 你认为这是什么问题?