Run this model with HF Jobs

Run proman007/Solace-2.5-2B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/proman007/Solace-2.5-2B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/proman007/Solace-2.5-2B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/proman007/Solace-2.5-2B. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/proman007/Solace-2.5-2B. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Solace-2.5-2B / scripts /train_stage3_polish.py
proman007's picture
Add model card, app.py, chat.py, docs, benchmarks, and training/export scripts
f1de719 verified
Raw History Blame Contribute Delete
6.95 kB
#!/usr/bin/env python3
"""
Stage 3: Long-Context (1536 tokens), Multi-Turn Memory, Identity & Safety Polish.
Merges final model in bfloat16 with clean Qwen3.5 EOS/generation defaults.
"""
import os
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
import argparse
import json
import math
import re
import time
import torch
import torch.nn.functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, get_cosine_schedule_with_warmup
import peft.import_utils as piu
piu.is_torchao_available = lambda: False
from peft import LoraConfig, TaskType, get_peft_model
ASST_RE = re.compile(
r"<\|im_start\|>assistant\n(?:<think>\n\n</think>\n\n)?(.*?<\|im_end\|>)",
flags=re.DOTALL,
)
TARGET_MODULES = [
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
"in_proj_qkv", "in_proj_z", "out_proj",
]
def encode_sft(msgs: list[dict], tok, max_len: int):
text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=False, enable_thinking=False)
enc = tok(text, return_offsets_mapping=True, truncation=True, max_length=max_len, add_special_tokens=False)
ids = enc["input_ids"]
offs = enc["offset_mapping"]
spans = [m.span(1) for m in ASST_RE.finditer(text)]
labels = [-100] * len(ids)
for idx, (a, b) in enumerate(offs):
if any(a >= s and b <= e and b > a for s, e in spans):
labels[idx] = ids[idx]
if sum(1 for x in labels[1:] if x != -100) < 2:
return None
return ids, labels
def forward_h(model, input_ids, labels):
inp = torch.tensor([input_ids], dtype=torch.long, device=model.device)
lbl = torch.tensor(labels[1:], dtype=torch.long, device=model.device)
out = model.get_base_model().model(input_ids=inp, use_cache=False)
h = out.last_hidden_state[0, :-1, :]
mask = lbl != -100
return h[mask], lbl[mask], int(mask.sum().item())
@torch.no_grad()
def eval_val(model, lm_head, val_samples, chunk_size=128):
model.eval()
tot_loss = 0.0
tot_tok = 0
for ids, labels in val_samples:
h_val, y_val, n_tok = forward_h(model, ids, labels)
for s in range(0, n_tok, chunk_size):
e = min(s + chunk_size, n_tok)
tot_loss += F.cross_entropy(lm_head(h_val[s:e]).float(), y_val[s:e], reduction="sum").item()
tot_tok += n_tok
model.train()
return tot_loss / max(1, tot_tok)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--s2-dir", default="/content/ckpt25/stage2_merged")
ap.add_argument("--train-json", default="/content/data25/stage3_train.json")
ap.add_argument("--val-json", default="/content/data25/stage3_val.json")
ap.add_argument("--out-dir", default="/content/ckpt25/solace_25_2b_final")
ap.add_argument("--max-len", type=int, default=1536)
ap.add_argument("--lr", type=float, default=4.5e-5)
ap.add_argument("--grad-accum", type=int, default=8)
ap.add_argument("--lora-r", type=int, default=16)
ap.add_argument("--lora-alpha", type=int, default=32)
args = ap.parse_args()
os.makedirs(args.out_dir, exist_ok=True)
tok = AutoTokenizer.from_pretrained(args.s2_dir)
if tok.pad_token_id is None:
tok.pad_token_id = tok.eos_token_id
train_data = [x for x in (encode_sft(m, tok, args.max_len) for m in json.load(open(args.train_json, encoding="utf-8"))) if x is not None]
val_data = [x for x in (encode_sft(m, tok, args.max_len) for m in json.load(open(args.val_json, encoding="utf-8"))) if x is not None]
print(f"[S3] Encoded train={len(train_data)} val={len(val_data)} max_len={args.max_len}", flush=True)
model = AutoModelForCausalLM.from_pretrained(args.s2_dir, dtype=torch.float16, device_map="auto")
model.config.use_cache = False
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
model.enable_input_require_grads()
lora_cfg = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=args.lora_r,
lora_alpha=args.lora_alpha,
lora_dropout=0.05,
bias="none",
target_modules=TARGET_MODULES,
)
model = get_peft_model(model, lora_cfg, autocast_adapter_dtype=True)
model.print_trainable_parameters()
lm_head = model.get_base_model().lm_head
opt_steps = max(1, (len(train_data) + args.grad_accum - 1) // args.grad_accum)
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=args.lr, weight_decay=0.01)
sched = get_cosine_schedule_with_warmup(opt, num_warmup_steps=max(4, int(0.08 * opt_steps)), num_training_steps=opt_steps)
scaler = torch.amp.GradScaler("cuda")
val0 = eval_val(model, lm_head, val_data)
print(f"[S3] Initial val_loss={val0:.4f} ppl={math.exp(val0):.3f}", flush=True)
model.train()
opt.zero_grad(set_to_none=True)
t0 = time.time()
running_loss = 0.0
for i, (ids, labels) in enumerate(train_data):
h_val, y_val, n_tok = forward_h(model, ids, labels)
grad_h = torch.zeros_like(h_val)
ex_loss = 0.0
for s in range(0, n_tok, 128):
e = min(s + 128, n_tok)
hc = h_val[s:e].detach().requires_grad_(True)
loss_c = F.cross_entropy(lm_head(hc).float(), y_val[s:e], reduction="sum") / n_tok
ex_loss += loss_c.detach().item()
(gh,) = torch.autograd.grad(scaler.scale(loss_c / args.grad_accum), hc)
grad_h[s:e] = gh
h_val.backward(grad_h)
running_loss += ex_loss
is_step = ((i + 1) % args.grad_accum == 0) or (i + 1 == len(train_data))
if is_step:
scaler.unscale_(opt)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(opt)
scaler.update()
sched.step()
opt.zero_grad(set_to_none=True)
if (i + 1) % 40 == 0 or (i + 1 == len(train_data)):
print(
f"[S3] ex={i+1}/{len(train_data)} avg_loss={running_loss/(i+1):.4f} "
f"elapsed={time.time()-t0:.1f}s peak_vram={torch.cuda.max_memory_allocated()/1e9:.2f}GB",
flush=True,
)
val1 = eval_val(model, lm_head, val_data)
print(f"[S3] Final val_loss={val1:.4f} ppl={math.exp(val1):.3f} total_time={time.time()-t0:.1f}s", flush=True)
merged = model.merge_and_unload().to(torch.bfloat16)
merged.config.eos_token_id = [248046, 248044]
merged.config.pad_token_id = 248044
merged.generation_config = GenerationConfig(
do_sample=True,
temperature=0.7,
top_p=0.9,
repetition_penalty=1.08,
max_new_tokens=768,
eos_token_id=[248046, 248044],
pad_token_id=248044,
)
merged.save_pretrained(args.out_dir, safe_serialization=True)
tok.save_pretrained(args.out_dir)
print(f"[S3] Saved final bf16 model to {args.out_dir}", flush=True)
if __name__ == "__main__":
main()