Feature Extraction
Transformers
TensorBoard
Safetensors
English
captionbert_v2
sentence-similarity
consensus-distillation
geometric-deep-learning
amoe
custom_code
Instructions to use AbstractPhil/captionbert-8192-v2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use AbstractPhil/captionbert-8192-v2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="AbstractPhil/captionbert-8192-v2", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("AbstractPhil/captionbert-8192-v2", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Update trainer_v1.py
Browse files41 unmodified lines42434445464766 unmodified lines114115116117118119426 unmodified lines54654754854955055155255355413 unmodified lines568569570571572573574110 unmodified lines68568668768868969069169269369469 unmodified lines76476576676776876915 unmodified lines7857867877887897907916 unmodified lines79879980080180280349 unmodified lines85385485585685785885986086186286341 unmodified linesexcept ImportError:subprocess.run([sys.executable, "-m", "pip", "install", "-q", _p], check=False)import numpy as npimport torchimport torch.nn as nn66 unmodified linesdropout: float = 0.1pooling: str = "mean" # arm: "cls". teachers are mean-pooledmax_tokens: int = 256 # dynamic pad ceiling# ββ training (sized for 95.6GB GPU: batch size IS the InfoNCE negative count) ββepochs: int = 4 # 13.7k steps/ep at 2048 -> ~55k total426 unmodified linesdef __init__(self, vocab_size=30522, max_len=8192, d_model=512, n_heads=8,n_layers=12, d_ff=2048, output_dim=768, dropout=0.1,pad_token_id=0, pooling="mean"):super().__init__()self.pad_token_id, self.pooling = pad_token_id, poolingself.token_emb = nn.Embedding(vocab_size, d_model, padding_idx=pad_token_id)self.pos_emb = nn.Embedding(max_len, d_model)self.emb_norm = nn.LayerNorm(d_model)13 unmodified linesx = self.emb_drop(self.emb_norm(self.token_emb(input_ids) + self.pos_emb(pos)))kpm = (~attention_mask.bool()) if attention_mask is not None \else (input_ids == self.pad_token_id)x = self.encoder(x, src_key_padding_mask=kpm)if self.pooling == "cls":pooled = x[:, 0]else:110 unmodified linesself.tgt = torch.cat(tgts)del tgts; gc.collect()self.n = len(self.offs) - 1gb = (self.flat.nbytes + self.offs.nbytes + self.tgt.numel() * 2) / 1e9mean_len = total / max(self.n, 1)print(f" RamStore{tag}: {self.n:,} rows | {gb:.1f} GB RAM | "f"mean {mean_len:.0f} tokens (ceiling {cfg.max_tokens})")def __len__(self):return self.n69 unmodified lines# STAGE 3 β TRAIN (cull-proof)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef save_state(cfg, path, student, opt, sched, scaler, step, epoch, chunk_i, order, best):torch.save({"model": student.state_dict(), "opt": opt.state_dict(),"sched": sched.state_dict(), "scaler": scaler.state_dict(),15 unmodified linesvocab_size=tok.vocab_size, max_len=cfg.max_len, d_model=cfg.d_model,n_heads=cfg.n_heads, n_layers=cfg.n_layers, d_ff=cfg.d_ff,output_dim=cfg.output_dim, dropout=cfg.dropout,pad_token_id=tok.pad_token_id, pooling=cfg.pooling).to(DEVICE)n_par = sum(p.numel() for p in student.parameters())train_chunks = [c for c in chunks if c not in cfg.holdout_chunks]rows = len(train_chunks) * src0(cfg)["chunk_rows"]6 unmodified linesprint(f" loss = {cfg.nce_weight}*InfoNCE(T={cfg.nce_temperature}) + "f"{cfg.mse_weight}*MSE + {cfg.cv_weight}*CV [champion consensus_nce_mse]")opt = torch.optim.Adam(student.parameters(), lr=cfg.lr) # pure Adam, no wdsched = torch.optim.lr_scheduler.SequentialLR(opt, [torch.optim.lr_scheduler.LinearLR(opt, 0.01, 1.0, cfg.warmup_steps),49 unmodified linest0 = last_ck = time.time()for ep in range(ep0, cfg.epochs):if cfg.ram_resident:# index permutation over the resident store; chunk_i doubles as batch indexperm = np.random.default_rng(cfg.seed + ep).permutation(N)for ci in range(chunk_i0 if ep == ep0 else 0, spe):ids, am, tg = train_src.batch(perm[ci * cfg.batch_size:(ci + 1) * cfg.batch_size])ids = ids.to(DEVICE, non_blocking=True)am = am.to(DEVICE, non_blocking=True)tgt = F.normalize(tg.to(DEVICE, non_blocking=True).float(), dim=-1)41 unmodified lines4243444546474849505166 unmodified lines118119120121122123124125126127128129130131132133134135136137426 unmodified lines56456556656756856957057157257313 unmodified lines587588589590591592593594595596597598110 unmodified lines70971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774869 unmodified lines81881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987015 unmodified lines8868878888898908918928936 unmodified lines90090190290390490590690790849 unmodified lines95895996096196296396496596696796896997097197297397497541 unmodified linesexcept ImportError:subprocess.run([sys.executable, "-m", "pip", "install", "-q", _p], check=False)# Variable-length batches fragment the caching allocator badly; this is the# documented mitigation and must be set BEFORE torch initialises CUDA.os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")import numpy as npimport torchimport torch.nn as nn66 unmodified linesdropout: float = 0.1pooling: str = "mean" # arm: "cls". teachers are mean-pooledmax_tokens: int = 256 # dynamic pad ceiling# OOM FIX (2026-07-31, observed at B=2048): dynamic padding pads to the BATCH# max, and with 2048 draws the max is essentially always the ceiling. The corpus# mean is 48 tokens but every batch ran at L=256 -- attention memory goes as L^2,# so 12 layers needed ~120 GB against 95 available.# length_bucketing sorts within a shuffled window so a batch is length-# homogeneous: L tracks the corpus mean (~48-64) instead of# the ceiling. ~5x less memory AND ~5x less compute.# grad_checkpointing bounds the worst case. The longest bucket IS a full batch# at L=256; checkpointing puts that at ~19 GB instead of# ~148 GB, for about 30% more compute.length_bucketing: bool = Truebucket_window: int = 64 # batches per sort windowgrad_checkpointing: bool = Truevram_probe: bool = True # forward+backward at worst case first# ββ training (sized for 95.6GB GPU: batch size IS the InfoNCE negative count) ββepochs: int = 4 # 13.7k steps/ep at 2048 -> ~55k total426 unmodified linesdef __init__(self, vocab_size=30522, max_len=8192, d_model=512, n_heads=8,n_layers=12, d_ff=2048, output_dim=768, dropout=0.1,pad_token_id=0, pooling="mean", grad_checkpointing=False):super().__init__()self.pad_token_id, self.pooling = pad_token_id, poolingself.grad_checkpointing = grad_checkpointingself.token_emb = nn.Embedding(vocab_size, d_model, padding_idx=pad_token_id)self.pos_emb = nn.Embedding(max_len, d_model)self.emb_norm = nn.LayerNorm(d_model)13 unmodified linesx = self.emb_drop(self.emb_norm(self.token_emb(input_ids) + self.pos_emb(pos)))kpm = (~attention_mask.bool()) if attention_mask is not None \else (input_ids == self.pad_token_id)if self.grad_checkpointing and self.training:for layer in self.encoder.layers:x = torch.utils.checkpoint.checkpoint(layer, x, None, kpm, use_reentrant=False)else:x = self.encoder(x, src_key_padding_mask=kpm)if self.pooling == "cls":pooled = x[:, 0]else:110 unmodified linesself.tgt = torch.cat(tgts)del tgts; gc.collect()self.n = len(self.offs) - 1self.lens = (self.offs[1:] - self.offs[:-1]).astype(np.int32)gb = (self.flat.nbytes + self.offs.nbytes + self.tgt.numel() * 2) / 1e9mean_len = total / max(self.n, 1)q = np.percentile(self.lens, [50, 90, 99, 100]).astype(int)print(f" RamStore{tag}: {self.n:,} rows | {gb:.1f} GB RAM | "f"mean {mean_len:.0f} tokens (ceiling {cfg.max_tokens})")print(f" length p50 {q[0]} | p90 {q[1]} | p99 {q[2]} | max {q[3]}"f" -- unbucketed, a batch pads to the BATCH MAX, i.e. ~{q[3]}")def plan_batches(self, batch_size, seed, window_batches=64, bucket=True):"""Deterministic batch plan for one epoch. Returns a list of index arrays.With bucket=True: shuffle, cut into windows of window_batches*batch_size,sort each window by length, slice into batches, then shuffle the BATCH ORDER.Batches end up length-homogeneous (so padding is near-free) while batchcomposition stays random across the window and the model never sees thecorpus in length order. Deterministic in (seed), so a resume mid-epochregenerates the identical plan and the stored batch index stays valid."""rng = np.random.default_rng(seed)perm = rng.permutation(self.n)if not bucket:n_full = self.n // batch_sizereturn [perm[i * batch_size:(i + 1) * batch_size] for i in range(n_full)]W = batch_size * max(window_batches, 1)batches = []for i in range(0, self.n, W):win = perm[i:i + W]win = win[np.argsort(self.lens[win], kind="stable")]for j in range(0, len(win) - batch_size + 1, batch_size):batches.append(win[j:j + batch_size])rng.shuffle(batches)return batchesdef __len__(self):return self.n69 unmodified lines# STAGE 3 β TRAIN (cull-proof)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef vram_probe(cfg, student):"""One forward+backward at the WORST case (full batch at the pad ceiling) beforeany data is loaded. With bucketing the longest bucket really is a full batch atmax_tokens, so this is the case that decides whether the run survives -- and itis far cheaper to discover here than 20 minutes into a RamStore build."""if DEVICE != "cuda":returnline("VRAM PROBE - worst-case batch before spending time on data")torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()total = torch.cuda.get_device_properties(0).total_memory / 1e9ids = torch.randint(1, 30000, (cfg.batch_size, cfg.max_tokens), device=DEVICE)am = torch.ones_like(ids)tgt = F.normalize(torch.randn(cfg.batch_size, cfg.output_dim, device=DEVICE), dim=-1)opt = torch.optim.Adam(student.parameters(), lr=1e-9)try:student.train()with torch.amp.autocast("cuda", enabled=cfg.amp):emb = student(ids, am)emb = emb.float()loss = infonce(emb, tgt, cfg.nce_temperature)[0] + F.mse_loss(emb, tgt)loss.backward()opt.zero_grad(set_to_none=True)peak = torch.cuda.max_memory_allocated() / 1e9print(f" batch {cfg.batch_size} x L {cfg.max_tokens} "f"(checkpointing={cfg.grad_checkpointing}) -> peak {peak:.1f} GB "f"of {total:.1f} GB")if peak > 0.85 * total:print(" !! within 15% of the limit. Reduce batch_size or max_tokens,")print(" !! or set grad_checkpointing=True, before starting the run.")else:ok = (total - peak)print(f" PASS - {ok:.1f} GB headroom")except torch.cuda.OutOfMemoryError:torch.cuda.empty_cache()raise RuntimeError(f"VRAM PROBE FAILED at batch {cfg.batch_size} x L {cfg.max_tokens} "f"(checkpointing={cfg.grad_checkpointing}). Options, cheapest first: "f"grad_checkpointing=True; lower max_tokens (corpus mean is ~48); "f"halve batch_size (costs InfoNCE negatives). Nothing was loaded, so "f"changing the config and re-running is quick.")finally:del ids, am, tgt, opttorch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()def save_state(cfg, path, student, opt, sched, scaler, step, epoch, chunk_i, order, best):torch.save({"model": student.state_dict(), "opt": opt.state_dict(),"sched": sched.state_dict(), "scaler": scaler.state_dict(),15 unmodified linesvocab_size=tok.vocab_size, max_len=cfg.max_len, d_model=cfg.d_model,n_heads=cfg.n_heads, n_layers=cfg.n_layers, d_ff=cfg.d_ff,output_dim=cfg.output_dim, dropout=cfg.dropout,pad_token_id=tok.pad_token_id, pooling=cfg.pooling,grad_checkpointing=cfg.grad_checkpointing).to(DEVICE)n_par = sum(p.numel() for p in student.parameters())train_chunks = [c for c in chunks if c not in cfg.holdout_chunks]rows = len(train_chunks) * src0(cfg)["chunk_rows"]6 unmodified linesprint(f" loss = {cfg.nce_weight}*InfoNCE(T={cfg.nce_temperature}) + "f"{cfg.mse_weight}*MSE + {cfg.cv_weight}*CV [champion consensus_nce_mse]")if cfg.vram_probe:vram_probe(cfg, student)opt = torch.optim.Adam(student.parameters(), lr=cfg.lr) # pure Adam, no wdsched = torch.optim.lr_scheduler.SequentialLR(opt, [torch.optim.lr_scheduler.LinearLR(opt, 0.01, 1.0, cfg.warmup_steps),49 unmodified linest0 = last_ck = time.time()for ep in range(ep0, cfg.epochs):if cfg.ram_resident:# deterministic bucketed plan; chunk_i doubles as the batch index, so a# mid-epoch resume regenerates the identical plan and lands on the same batchplan = train_src.plan_batches(cfg.batch_size, cfg.seed + ep,cfg.bucket_window, cfg.length_bucketing)if ep == ep0:spe = len(plan); total = spe * cfg.epochsbl = np.array([train_src.lens[b].max() for b in plan[:200]])print(f" batch plan: {spe:,} batches/epoch | padded length "f"p50 {int(np.percentile(bl,50))} p90 {int(np.percentile(bl,90))} "f"max {int(bl.max())} (bucketing={cfg.length_bucketing})")for ci in range(chunk_i0 if ep == ep0 else 0, len(plan)):ids, am, tg = train_src.batch(plan[ci])ids = ids.to(DEVICE, non_blocking=True)am = am.to(DEVICE, non_blocking=True)tgt = F.normalize(tg.to(DEVICE, non_blocking=True).float(), dim=-1)
trainer_v1.py+120-8