exp48 protocol on conversational/bigger models (exp50): multimodal + pre-quantized 4-bit loading, template-safe BOS, generic layer lookup; pod launcher --models/--gpu list/--volume

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EandClaude Opus 5.5 committed 2026-10-02 15:49:09 -04:00
1 parent dcdb4e8a2d
commit 0f8a214485
2 files changed
+46 -17

No files matched your search

+24 -8
View File
@@ -272,11 +272,22 @@ def main():
dev = args.device
tok = transformers.AutoTokenizer.from_pretrained(MODEL, revision=REVISION)
model = transformers.AutoModelForCausalLM.from_pretrained(
MODEL, revision=REVISION, dtype=torch.bfloat16).to(dev).eval()
model.requires_grad_(False)
kw = dict(revision=REVISION, dtype=torch.bfloat16)
if "bnb-4bit" in MODEL: # pre-quantized: weights load straight onto the GPU
kw["device_map"] = dev
try:
model = transformers.AutoModelForCausalLM.from_pretrained(MODEL, **kw)
except ValueError: # multimodal wrappers (Mistral 3): text path is the same
model = transformers.AutoModelForImageTextToText.from_pretrained(MODEL, **kw)
if "device_map" not in kw:
model = model.to(dev)
model.eval().requires_grad_(False)
layers = next(m.layers for m in (getattr(model, "model", None),
getattr(getattr(model, "model", None), "language_model", None),
getattr(model, "language_model", None))
if m is not None and hasattr(m, "layers"))
LAYER = args.layer if args.layer is not None else (
18 if MODEL == "Qwen/Qwen3-4B" else model.config.num_hidden_layers // 2)
18 if MODEL == "Qwen/Qwen3-4B" else len(layers) // 2)
(out / "hypotheses.json").write_text(json.dumps(hypotheses(tag), indent=1))
# the J-lens file is Qwen3-4B's layer 18 only
lens = (torch.load(LENS, map_location=dev, weights_only=True)
@@ -323,14 +334,19 @@ def main():
if state["v"] is not None:
h[0, -1, :] += state["v"].to(h.dtype)
return (h,) + o[1:] if isinstance(o, tuple) else h
model.model.layers[LAYER].register_forward_hook(hook)
layers[LAYER].register_forward_hook(hook)
def set_vec(name, dose):
state["v"] = None if name is None or dose == 0 else (dose * vec[name]).to(dev)
def chat_ids(prompt):
text = tok.apply_chat_template([{"role": "user", "content": prompt}], tokenize=False,
add_generation_prompt=True, enable_thinking=False)
return tok(text, return_tensors="pt").input_ids.to(dev)
msgs = [{"role": "user", "content": prompt}]
if tok.chat_template:
text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True,
enable_thinking=False)
else: # no template shipped: Mistral instruct format
text = f"<s>[INST]{prompt}[/INST]"
# the template already carries any BOS token; don't add a second one
return tok(text, return_tensors="pt", add_special_tokens=False).input_ids.to(dev)
def generate(prompt, name, dose):
ids = chat_ids(prompt)
+22 -9
View File
@@ -13,10 +13,26 @@ ap = argparse.ArgumentParser()
ap.add_argument("--big", default="Qwen/Qwen3-14B")
ap.add_argument("--script", default="exp48_emotion_binding.py",
help="experiment script; results are served from runs/<expNN>/")
ap.add_argument("--gpu", default="NVIDIA RTX A6000")
ap.add_argument("--gpu", default="NVIDIA RTX A6000,NVIDIA L40S", help="comma-separated, in preference order")
ap.add_argument("--models", default=None,
help="comma-separated HF ids: run smoke+full for each in turn, continuing past "
"a failed model (marker FAILED_<name>), instead of the smoke/4B/big chain")
ap.add_argument("--volume", type=int, default=80)
ap.add_argument("--pod", default=None, help="update this existing pod's start command instead of creating one")
args = ap.parse_args()
EXP = args.script.split("_")[0] # e.g. exp49
if args.models: # per-model smoke then full; a failed model is marked and skipped
RUNS = "\n".join(
f"n={m.split('/')[-1]}; log \"$n\"; "
f"python {{SCRIPT}} --smoke --device cuda --model {m} > runs/{{EXP}}/$n.smoke.log 2>&1 && "
f"python {{SCRIPT}} --device cuda --model {m} > runs/{{EXP}}/$n.log 2>&1 "
f"|| {{ log \"$n FAILED\"; touch runs/{{EXP}}/FAILED_$n; }}"
for m in args.models.split(","))
else:
RUNS = """run(){ log "$1"; shift; "$@" || { log "FAILED"; touch runs/{EXP}/FAILED; sleep infinity; }; }
run smoke sh -c 'python {SCRIPT} --smoke --device cuda > runs/{EXP}/smoke_gpu.log 2>&1'
run full-4B sh -c 'python {SCRIPT} --device cuda > runs/{EXP}/full.log 2>&1'
run big sh -c 'python {SCRIPT} --device cuda --model {BIG} > runs/{EXP}/big.log 2>&1'"""
key = [l.split("=", 1)[1].strip() for l in open(pathlib.Path.home() / ".hermes/.env")
if l.startswith("RUNPOD_API_KEY=")][0]
@@ -35,20 +51,17 @@ mkdir -p runs/{EXP}
(cd runs/{EXP} && python -m http.server 8000 >/dev/null 2>&1 &)
log "deps"
pip install -q --no-cache-dir 'torch==2.8.0' --index-url https://download.pytorch.org/whl/cu128 > runs/{EXP}/pip.log 2>&1
pip install -q --no-cache-dir 'transformers==5.17.0' numpy accelerate >> runs/{EXP}/pip.log 2>&1
pip install -q --no-cache-dir 'transformers==5.17.0' numpy accelerate bitsandbytes mistral-common >> runs/{EXP}/pip.log 2>&1
# the base image's torchvision/torchaudio are built for torch 2.4 and break
# transformers' lazy model imports ("Could not import module Qwen3ForCausalLM")
pip uninstall -y -q torchvision torchaudio >> runs/{EXP}/pip.log 2>&1
python -c "import torch; assert torch.cuda.is_available(); print(torch.__version__, torch.cuda.get_device_name())" > runs/{EXP}/env.txt 2>&1 || { log "no CUDA"; sleep infinity; }
python -c "import transformers.models.qwen3.modeling_qwen3 as m; print('qwen3 import ok', m.__name__)" >> runs/{EXP}/env.txt 2>&1 || { log "import broken"; touch runs/{EXP}/FAILED; sleep infinity; }
export HF_HOME=/workspace/hf
run(){ log "$1"; shift; "$@" || { log "FAILED"; touch runs/{EXP}/FAILED; sleep infinity; }; }
run smoke sh -c 'python {SCRIPT} --smoke --device cuda > runs/{EXP}/smoke_gpu.log 2>&1'
run full-4B sh -c 'python {SCRIPT} --device cuda > runs/{EXP}/full.log 2>&1'
run big sh -c 'python {SCRIPT} --device cuda --model {BIG} > runs/{EXP}/big.log 2>&1'
{RUNS}
log "done"; touch runs/{EXP}/ALL_DONE
sleep infinity
""".replace("{REPO_URL}", REPO_URL).replace("{BIG}", args.big).replace(
""".replace("{RUNS}", RUNS).replace("{REPO_URL}", REPO_URL).replace("{BIG}", args.big).replace(
"{EXP}", EXP).replace("{SCRIPT}", args.script)
def rest(method, path, body=None):
@@ -70,9 +83,9 @@ pod = rest("POST", "pods", {
# REST v1 PodCreateInput (schema: https://rest.runpod.io/v1/openapi.json)
"name": f"{EXP}-pod",
"imageName": "pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime",
"gpuTypeIds": [args.gpu, "NVIDIA L40S"], "gpuTypePriority": "custom",
"gpuTypeIds": [g.strip() for g in args.gpu.split(",")], "gpuTypePriority": "custom",
"gpuCount": 1, "cloudType": "SECURE",
"ports": ["8000/http"], "volumeInGb": 80, "volumeMountPath": "/workspace",
"ports": ["8000/http"], "volumeInGb": args.volume, "volumeMountPath": "/workspace",
"containerDiskInGb": 40, "env": {"HF_HOME": "/workspace/hf"},
"dockerEntrypoint": ["/bin/bash", "-c"], "dockerStartCmd": [BOOTSTRAP],
})