Resumable Kaggle evaluations, sequential SliceGPT LoRA and exported Modal progress
Browse files- README.md +99 -49
- bundle_manifest.json +1 -1
- finetune_runner.py +102 -0
- kaggle_lm_eval.ipynb +235 -0
- kaggle_slicegpt_lora.ipynb +164 -0
- portable_eval.zip +2 -2
- portable_lm_eval.ipynb +140 -84
- run_suite.py +98 -0
- runner.py +128 -51
README.md
CHANGED
|
@@ -1,49 +1,99 @@
|
|
| 1 |
-
#
|
| 2 |
-
|
| 3 |
-
Download
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kaggle, Colab and other GPU evaluation
|
| 2 |
+
|
| 3 |
+
Download kaggle_lm_eval.ipynb from the public dataset
|
| 4 |
+
https://huggingface.co/datasets/vanshnawander/structured-diffusion-eval
|
| 5 |
+
and import it into Kaggle. Enable Internet and GPU in notebook settings.
|
| 6 |
+
No Modal account or HF token is needed to download the 27 public pruned models.
|
| 7 |
+
|
| 8 |
+
The notebook defaults to one selected checkpoint. Change MODEL_INDEX or REPOS
|
| 9 |
+
for each GPU session. EVALUATE_ALL_MODELS=True selects all 27 original pruned
|
| 10 |
+
checkpoints. NUM_WORKERS and WORKER_INDEX partition checkpoint/task pairs exactly
|
| 11 |
+
once between independent sessions. All seven benchmarks (ARC-Easy, Winogrande,
|
| 12 |
+
PIQA, ARC-Challenge, HellaSwag, BoolQ, GSM8K) and both WikiText-2/C4 perplexities
|
| 13 |
+
are enabled. The full grid is 189 benchmark tasks plus 54 PPL datasets.
|
| 14 |
+
|
| 15 |
+
The authoritative config is copied from
|
| 16 |
+
Pruning-LLMs/diffusion_eval_and_vis/config.py. The notebook prints the complete
|
| 17 |
+
effective config, adapter arguments and assignments before loading weights.
|
| 18 |
+
MC samples remain 128; generation stays at 256 steps, LLaDA length/block 1024,
|
| 19 |
+
Dream length 256, seed 42, original guidance/remasking, five-shot GSM8K and
|
| 20 |
+
zero-shot other tasks. It does not reduce dataset sizes or generation lengths.
|
| 21 |
+
|
| 22 |
+
The shared profile keeps BF16 and MC mini-batch 32. The explicit kaggle profile
|
| 23 |
+
uses mini-batch 1 with dtype=auto (FP16 on T4, BF16 on supporting hardware).
|
| 24 |
+
This changes precision and the stochastic mini-batch grouping. Use the same
|
| 25 |
+
profile for all comparisons. Profiles/revisions have separate output directories
|
| 26 |
+
and merge groups. CPU/disk offload preserves model weights; there is no
|
| 27 |
+
quantization. Auto device mapping can use both GPUs in a T4 x2 session. One
|
| 28 |
+
evaluation is model-sharded; this is not two independent replicas.
|
| 29 |
+
|
| 30 |
+
Model snapshots/offload weights go in /kaggle/temp, outside saved outputs.
|
| 31 |
+
Only evaluation results, response caches and RNG/PPL recovery state are saved
|
| 32 |
+
in /kaggle/working/results. Likelihood saves each response in the notebook;
|
| 33 |
+
generation saves each answer; perplexity saves each completed sequence.
|
| 34 |
+
SESSION_HOURS defaults to 8. The runner commits progress and returns before
|
| 35 |
+
the platform deadline; time budgets are checked between requests/sequences,
|
| 36 |
+
so one outstanding request may finish after the budget.
|
| 37 |
+
|
| 38 |
+
Use Save Version > Save & Run All for background execution on Kaggle.
|
| 39 |
+
The final cell produces evaluation_results_worker-<index>.zip. Download/save
|
| 40 |
+
outputs before discarding an interactive session. Attach that output to the
|
| 41 |
+
next notebook, set RESTORE_ZIP to the archive path under /kaggle/input, and
|
| 42 |
+
rerun with the same config and SHA. Scores already computed are replayed
|
| 43 |
+
without another forward pass. Resumption retains RNG state; hardware/precision
|
| 44 |
+
changes can still alter floating-point results.
|
| 45 |
+
|
| 46 |
+
Existing Modal results/partial responses are available in modal_progress.zip.
|
| 47 |
+
IMPORT_MODAL_PROGRESS=True imports them into the original BF16/32 profile.
|
| 48 |
+
They are not reused for FP16/1 evaluations. Saved original pruning models and
|
| 49 |
+
unfinished LoRA recovery files remain preserved. No paid Modal work runs.
|
| 50 |
+
|
| 51 |
+
Original SliceGPT uploads are pruned baselines. None completed the requested
|
| 52 |
+
sequential LoRA before the budget stop. Select a final fine-tuned repository
|
| 53 |
+
and enable REQUIRE_FINETUNED_SLICE to enforce post-LoRA evaluation; this guard
|
| 54 |
+
refuses a baseline without finetune_manifest.json. Baseline SliceGPT scores
|
| 55 |
+
must not be presented as fine-tuned scores.
|
| 56 |
+
|
| 57 |
+
For a terminal, extract portable_eval.zip and install requirements.txt:
|
| 58 |
+
|
| 59 |
+
python portable_eval/runner.py --show-config --repo MODEL
|
| 60 |
+
python portable_eval/run_suite.py --repos MODEL --batch-size 1 --dtype auto --output results --time-budget-seconds 28800
|
| 61 |
+
python portable_eval/run_suite.py --repos MODEL --num-workers 3 --worker-index 0 --batch-size 1 --dtype auto --output results
|
| 62 |
+
python portable_eval/runner.py --repo MODEL --units ppl:c4 --batch-size 1 --dtype auto --output results
|
| 63 |
+
python portable_eval/runner.py --repo MODEL --tasks piqa --limit 2 --skip-ppl --batch-size 1 --dtype auto --output smoke_results
|
| 64 |
+
|
| 65 |
+
Omit --repos to assign the entire 27-model grid. Use --plan to preview without
|
| 66 |
+
a GPU. Full evaluations omit --limit. Smoke outputs stay separate from full
|
| 67 |
+
metrics. To combine worker outputs, extract ZIPs into a common directory:
|
| 68 |
+
|
| 69 |
+
python portable_eval/runner.py --merge combined/results --output merged_results.json
|
| 70 |
+
|
| 71 |
+
The merger includes benchmark and PPL metrics, rejects conflicting duplicates,
|
| 72 |
+
and never combines different checkpoint SHAs/effective settings into one row.
|
| 73 |
+
|
| 74 |
+
Verification uses local tiny LLaDA/Dream models for each pruning method, real
|
| 75 |
+
lm-eval scoring, sliced precision conversion/offload, and uninterrupted versus
|
| 76 |
+
resumed PPL equality. This is not a full 7B/8B run inside a Kaggle account.
|
| 77 |
+
|
| 78 |
+
References: https://www.kaggle.com/docs/notebooks
|
| 79 |
+
https://github.com/EleutherAI/lm-evaluation-harness
|
| 80 |
+
https://huggingface.co/docs/accelerate/concept_guides/big_model_inference
|
| 81 |
+
|
| 82 |
+
The companion kaggle_slicegpt_lora.ipynb completes the nine unfinished sequential
|
| 83 |
+
fine-tunes using the same diffusion objective and LoRA hyperparameters. Choose
|
| 84 |
+
one original SliceGPT source per session, use both T4 GPUs or a larger GPU, and
|
| 85 |
+
keep all weights on GPUs. The trainer refuses CPU/disk training offload.
|
| 86 |
+
FP16 training is explicitly recorded as a separate precision profile; matching
|
| 87 |
+
BF16 training requires supporting hardware. It checkpoints and exits at the
|
| 88 |
+
session time budget, relocates recovery paths when restoring notebook output,
|
| 89 |
+
merges/reloads/verifies, and can upload a public HF checkpoint using HF_TOKEN
|
| 90 |
+
from Kaggle Secrets. Evaluation follows in a separate notebook with the uploaded
|
| 91 |
+
repo and REQUIRE_FINETUNED_SLICE=True. This guard is enabled by default in the
|
| 92 |
+
evaluation notebook, so original SliceGPT baseline scores require an explicit
|
| 93 |
+
opt-out.
|
| 94 |
+
|
| 95 |
+
The two paid BF16 LoRA recovery states are downloadable as
|
| 96 |
+
modal_training_recovery.zip. RESTORE_MODAL_BF16=True in the training notebook
|
| 97 |
+
imports the chosen saved optimizer/adapter state, relocates its paths and
|
| 98 |
+
requires the unchanged BF16 training configuration. Sources which never started
|
| 99 |
+
have no recovery state. FP16 training intentionally starts a separate run.
|
bundle_manifest.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
{
|
| 2 |
"run_id": "run-9fc515e82f313fab",
|
| 3 |
-
"zip_sha256": "
|
| 4 |
"available_checkpoints": 27,
|
| 5 |
"shared_config": "Pruning-LLMs/diffusion_eval_and_vis/config.py",
|
| 6 |
"smoke_tests": "All three methods on tiny LLaDA/Dream: likelihood, generation, CPU/disk and CUDA fp16 offload, reload agreement; task sharding and merging"
|
|
|
|
| 1 |
{
|
| 2 |
"run_id": "run-9fc515e82f313fab",
|
| 3 |
+
"zip_sha256": "89b29760ba2b7ab074568c6480277a7e859b9b80bd1f8dc3f0d9afba6977e123",
|
| 4 |
"available_checkpoints": 27,
|
| 5 |
"shared_config": "Pruning-LLMs/diffusion_eval_and_vis/config.py",
|
| 6 |
"smoke_tests": "All three methods on tiny LLaDA/Dream: likelihood, generation, CPU/disk and CUDA fp16 offload, reload agreement; task sharding and merging"
|
finetune_runner.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sequential SliceGPT diffusion LoRA on a free/local GPU; optional public HF upload."""
|
| 2 |
+
import argparse
|
| 3 |
+
from dataclasses import asdict
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 11 |
+
from diffusion_eval_and_vis.config import StructuredPruningConfig
|
| 12 |
+
from runner import write_json
|
| 13 |
+
import training_core
|
| 14 |
+
|
| 15 |
+
DATASET_REVISIONS = {
|
| 16 |
+
"wikitext2": "b08601e04326c79dfdd32d625aee71d232d685c3",
|
| 17 |
+
"c4": "1588ec454efa1a09f29cd18ddd04fe05fc8653a2",
|
| 18 |
+
"alpaca": "dce01c9b08f87459cf36a430d809084718273017",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
def relocate_resume(root):
|
| 22 |
+
path = root / "resume.json"
|
| 23 |
+
if path.exists():
|
| 24 |
+
state = json.loads(path.read_text())
|
| 25 |
+
for key in ["adapter", "runtime"]:
|
| 26 |
+
parts = Path(state[key]).parts
|
| 27 |
+
position = next(i for i, part in enumerate(parts) if part.startswith("resume_"))
|
| 28 |
+
state[key] = str(root.joinpath(*parts[position:]))
|
| 29 |
+
write_json(path, state)
|
| 30 |
+
saved_path = root / "saved.json"
|
| 31 |
+
if saved_path.exists():
|
| 32 |
+
saved = json.loads(saved_path.read_text())
|
| 33 |
+
saved["checkpoint_path"] = str(root / "merged")
|
| 34 |
+
write_json(saved_path, saved)
|
| 35 |
+
|
| 36 |
+
def main():
|
| 37 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 38 |
+
p.add_argument("--repo", required=True)
|
| 39 |
+
p.add_argument("--revision")
|
| 40 |
+
p.add_argument("--output", default="training_results")
|
| 41 |
+
p.add_argument("--cache-dir", default=".training_hf_cache")
|
| 42 |
+
p.add_argument("--offload-dir", default=".training_offload")
|
| 43 |
+
p.add_argument("--dtype", choices=["bfloat16", "float16"], default="bfloat16")
|
| 44 |
+
p.add_argument("--device", default="cuda")
|
| 45 |
+
p.add_argument("--device-map", choices=["auto", "single"], default="auto")
|
| 46 |
+
p.add_argument("--time-budget-seconds", type=float, default=8*3600)
|
| 47 |
+
p.add_argument("--show-config", action="store_true")
|
| 48 |
+
p.add_argument("--restore-training-dir", help="Original training/<job> or prior notebook recovery folder")
|
| 49 |
+
p.add_argument("--upload", action="store_true", help="Save/reload/verify, then upload publicly with HF_TOKEN")
|
| 50 |
+
p.add_argument("--namespace", default="vanshnawander")
|
| 51 |
+
args = p.parse_args()
|
| 52 |
+
cfg = StructuredPruningConfig()
|
| 53 |
+
cfg.eval.dtype, cfg.eval.device = args.dtype, args.device
|
| 54 |
+
if args.show_config:
|
| 55 |
+
print(json.dumps({"finetune_config": asdict(cfg.finetune), "eval_config": asdict(cfg.eval),
|
| 56 |
+
"dataset_revisions": DATASET_REVISIONS}, indent=2))
|
| 57 |
+
return
|
| 58 |
+
import torch
|
| 59 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 60 |
+
if not torch.cuda.is_available():
|
| 61 |
+
raise RuntimeError("Enable GPU(s). CPU/disk inference offload cannot be used for LoRA training.")
|
| 62 |
+
if args.dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
|
| 63 |
+
raise RuntimeError("Select float16 explicitly on T4; the precision override is recorded.")
|
| 64 |
+
token = os.environ.get("HF_TOKEN", False)
|
| 65 |
+
revision = args.revision or HfApi(token=token).model_info(args.repo).sha
|
| 66 |
+
manifest = json.loads(Path(hf_hub_download(args.repo, "checkpoint_manifest.json", revision=revision,
|
| 67 |
+
token=token)).read_text())
|
| 68 |
+
job = manifest.get("job", manifest.get("provenance", {}).get("job"))
|
| 69 |
+
if not job or job["method"] != "slicegpt" or "provenance" in manifest:
|
| 70 |
+
raise ValueError("Choose an original SliceGPT checkpoint for sequential LoRA training.")
|
| 71 |
+
upload = {"repo_id": args.repo, "commit_sha": revision, "url": "https://huggingface.co/" + args.repo}
|
| 72 |
+
# Different training precisions must never overwrite each other's merged models.
|
| 73 |
+
profile = hashlib.sha256(json.dumps({"dtype": args.dtype, "finetune": asdict(cfg.finetune)}, sort_keys=True).encode()).hexdigest()[:8]
|
| 74 |
+
identifier = "run-9fc515e82f313fab-kaggle-" + profile
|
| 75 |
+
training_core.RUNS = Path(args.output).resolve()
|
| 76 |
+
os.environ["TRAIN_HF_CACHE"] = args.cache_dir
|
| 77 |
+
os.environ["TRAIN_OFFLOAD_DIR"] = args.offload_dir
|
| 78 |
+
os.environ["TRAIN_DEVICE_MAP"] = args.device_map
|
| 79 |
+
from training_support import Job
|
| 80 |
+
root = training_core.RUNS / identifier / "pipeline/training" / Job(**job).name
|
| 81 |
+
if args.restore_training_dir and not (root / "resume.json").exists():
|
| 82 |
+
import shutil
|
| 83 |
+
shutil.copytree(args.restore_training_dir, root, dirs_exist_ok=True)
|
| 84 |
+
relocate_resume(root)
|
| 85 |
+
if (root / "uploaded.json").exists():
|
| 86 |
+
uploaded = json.loads((root / "uploaded.json").read_text())
|
| 87 |
+
saved = json.loads((root / "saved.json").read_text())
|
| 88 |
+
from training_support import verify_remote_files
|
| 89 |
+
verify_remote_files(HfApi(token=token), uploaded["repo_id"], uploaded["commit_sha"], saved["files"])
|
| 90 |
+
print(json.dumps(uploaded, indent=2))
|
| 91 |
+
return
|
| 92 |
+
result = training_core.train_one(asdict(cfg), identifier, job, upload, DATASET_REVISIONS,
|
| 93 |
+
lambda: None, deadline=time.monotonic()+args.time_budget_seconds)
|
| 94 |
+
print(json.dumps(result, indent=2), flush=True)
|
| 95 |
+
if args.upload and not result.get("continued"):
|
| 96 |
+
if not os.environ.get("HF_TOKEN"):
|
| 97 |
+
raise RuntimeError("Set HF_TOKEN in Kaggle Secrets for the requested public upload.")
|
| 98 |
+
uploaded = training_core.upload_finetuned(identifier, job, args.namespace, lambda: None)
|
| 99 |
+
print(json.dumps(uploaded, indent=2), flush=True)
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
main()
|
kaggle_lm_eval.ipynb
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 5,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"kernelspec": {
|
| 6 |
+
"display_name": "Python 3",
|
| 7 |
+
"language": "python",
|
| 8 |
+
"name": "python3"
|
| 9 |
+
},
|
| 10 |
+
"language_info": {
|
| 11 |
+
"name": "python"
|
| 12 |
+
}
|
| 13 |
+
},
|
| 14 |
+
"cells": [
|
| 15 |
+
{
|
| 16 |
+
"cell_type": "markdown",
|
| 17 |
+
"metadata": {},
|
| 18 |
+
"source": [
|
| 19 |
+
"# Evaluate pruned LLaDA/Dream on Kaggle or Colab\n",
|
| 20 |
+
"Enable **Internet** and a **GPU**. This notebook downloads public Hugging Face checkpoints and never calls Modal.\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"All seven benchmarks and both perplexity datasets are enabled. Choose one checkpoint per session, or shard the 27-checkpoint grid across sessions. Generation uses 256 steps, LLaDA length/block 1024, Dream length 256; likelihood uses MC 128. GSM8K retains five shots.\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"The kaggle profile explicitly uses MC mini-batch 1 and supported precision (FP16 on T4). MC sample count and generation settings stay unchanged, while precision/mini-batch differ from Modal BF16/32. Results stay separate by config. Use the shared profile on hardware that supports the original settings.\n",
|
| 25 |
+
"\nOriginal SliceGPT checkpoints require sequential LoRA first by default. Use the companion kaggle_slicegpt_lora.ipynb, then evaluate the final uploaded repo. Disable REQUIRE_FINETUNED_SLICE only to explicitly request baseline scores.\n"
|
| 26 |
+
],
|
| 27 |
+
"id": "cell-0"
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"source": [
|
| 33 |
+
"import sys, subprocess, os, json, hashlib, zipfile\n",
|
| 34 |
+
"from pathlib import Path\n",
|
| 35 |
+
"subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"huggingface-hub==0.36.0\"])\n",
|
| 36 |
+
"from huggingface_hub import HfApi, hf_hub_download\n",
|
| 37 |
+
"WORK_DIR = Path(\"/kaggle/working\") if Path(\"/kaggle\").exists() else Path.cwd()\n",
|
| 38 |
+
"TEMP_DIR = Path(\"/kaggle/temp\") if Path(\"/kaggle\").exists() else Path(\"/tmp\")\n",
|
| 39 |
+
"TEMP_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 40 |
+
"BUNDLE_REPO = \"vanshnawander/structured-diffusion-eval\"\n",
|
| 41 |
+
"release = HfApi(token=False).dataset_info(BUNDLE_REPO).sha\n",
|
| 42 |
+
"bundle = hf_hub_download(BUNDLE_REPO, \"portable_eval.zip\", repo_type=\"dataset\", revision=release, token=False)\n",
|
| 43 |
+
"manifest = json.loads(Path(hf_hub_download(BUNDLE_REPO, \"bundle_manifest.json\", repo_type=\"dataset\", revision=release, token=False)).read_text())\n",
|
| 44 |
+
"assert hashlib.sha256(Path(bundle).read_bytes()).hexdigest() == manifest[\"zip_sha256\"]\n",
|
| 45 |
+
"SOURCE_DIR = TEMP_DIR / \"structured_eval_source\"\n",
|
| 46 |
+
"SOURCE_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 47 |
+
"with zipfile.ZipFile(bundle) as archive:\n",
|
| 48 |
+
" archive.extractall(SOURCE_DIR)\n",
|
| 49 |
+
"EVAL_ROOT = SOURCE_DIR / \"portable_eval\"\n",
|
| 50 |
+
"subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-r\", str(EVAL_ROOT / \"requirements.txt\")])\n",
|
| 51 |
+
"print(\"Verified evaluation release:\", release)\n"
|
| 52 |
+
],
|
| 53 |
+
"execution_count": null,
|
| 54 |
+
"outputs": [],
|
| 55 |
+
"id": "cell-1"
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "markdown",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"If packages were already imported before installation, restart the kernel and rerun setup. Existing PyTorch is kept when it meets the requirements. Model weights and offload files use /kaggle/temp; saved outputs contain only results and evaluation resume state.\n"
|
| 62 |
+
],
|
| 63 |
+
"id": "cell-2"
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"catalog = json.loads((EVAL_ROOT / \"models.json\").read_text())\n",
|
| 70 |
+
"for i, row in enumerate(catalog):\n",
|
| 71 |
+
" print(i, row[\"repo_id\"])\n",
|
| 72 |
+
"MODEL_INDEX = 0\n",
|
| 73 |
+
"REPOS = [catalog[MODEL_INDEX][\"repo_id\"]] # May also contain a final fine-tuned HF repository.\n",
|
| 74 |
+
"EVALUATE_ALL_MODELS = False # True selects all 27 original pruned checkpoints.\n",
|
| 75 |
+
"WORKER_INDEX = 0\n",
|
| 76 |
+
"NUM_WORKERS = 1 # Same count, distinct indices in parallel sessions.\n",
|
| 77 |
+
"PROFILE = \"kaggle\" # \"shared\" = authoritative BF16 / MC mini-batch 32.\n",
|
| 78 |
+
"SESSION_HOURS = 8 # End gracefully before the platform deadline.\n",
|
| 79 |
+
"TASKS = None # None = all seven tasks, including GSM8K.\n",
|
| 80 |
+
"RUN_PPL = True # WikiText-2 and C4, as in the shared config.\n",
|
| 81 |
+
"REQUIRE_FINETUNED_SLICE = True # True rejects original SliceGPT baselines.\n",
|
| 82 |
+
"RUN_FORWARD_SMOKE = True\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"# Original SliceGPT repositories are PRUNED BASELINES, not completed LoRA fine-tunes.\n",
|
| 85 |
+
"# No sequential LoRA fine-tune completed before Modal was stopped for the budget.\n",
|
| 86 |
+
"OUTPUT_DIR = WORK_DIR / \"results\"\n",
|
| 87 |
+
"CACHE_DIR = TEMP_DIR / \"structured_eval_hf\"\n",
|
| 88 |
+
"OFFLOAD_DIR = TEMP_DIR / \"structured_eval_offload\"\n",
|
| 89 |
+
"OUTPUT_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 90 |
+
"RESTORE_ZIP = \"\" # /kaggle/input/previous-results/evaluation_results_worker-0.zip\n",
|
| 91 |
+
"IMPORT_MODAL_PROGRESS = False # BF16/32 scores are not reused by the FP16/1 profile.\n"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": [],
|
| 95 |
+
"id": "cell-3"
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"import torch\n",
|
| 102 |
+
"print(\"GPUs:\", [(i, torch.cuda.get_device_name(i)) for i in range(torch.cuda.device_count())])\n",
|
| 103 |
+
"if not torch.cuda.is_available():\n",
|
| 104 |
+
" raise RuntimeError(\"Enable a GPU runtime in Kaggle/Colab settings.\")\n",
|
| 105 |
+
"assert PROFILE in {\"shared\", \"kaggle\"}\n",
|
| 106 |
+
"RESOURCE_ARGS = [] if PROFILE == \"shared\" else [\"--batch-size\", \"1\", \"--dtype\", \"auto\"]\n",
|
| 107 |
+
"if PROFILE == \"shared\" and not torch.cuda.is_bf16_supported():\n",
|
| 108 |
+
" raise RuntimeError(\"This GPU does not support BF16. Choose PROFILE='kaggle' explicitly.\")\n",
|
| 109 |
+
"BASE = [sys.executable, str(EVAL_ROOT / \"runner.py\"), \"--device\", \"cuda\",\n",
|
| 110 |
+
" \"--device-map\", \"auto\", \"--gpu-memory-ratio\", \"0.65\",\n",
|
| 111 |
+
" \"--cache-dir\", str(CACHE_DIR), \"--offload-dir\", str(OFFLOAD_DIR)] + RESOURCE_ARGS\n",
|
| 112 |
+
"SUITE = [sys.executable, str(EVAL_ROOT / \"run_suite.py\"),\n",
|
| 113 |
+
" \"--worker-index\", str(WORKER_INDEX), \"--num-workers\", str(NUM_WORKERS),\n",
|
| 114 |
+
" \"--output\", str(OUTPUT_DIR), \"--cache-dir\", str(CACHE_DIR),\n",
|
| 115 |
+
" \"--offload-dir\", str(OFFLOAD_DIR), \"--time-budget-seconds\", str(SESSION_HOURS * 3600),\n",
|
| 116 |
+
" \"--request-chunk-size\", \"1\"] + RESOURCE_ARGS\n",
|
| 117 |
+
"if not EVALUATE_ALL_MODELS:\n",
|
| 118 |
+
" SUITE += [\"--repos\", *REPOS]\n",
|
| 119 |
+
"if TASKS:\n",
|
| 120 |
+
" SUITE += [\"--tasks\", *TASKS]\n",
|
| 121 |
+
"if not RUN_PPL:\n",
|
| 122 |
+
" SUITE += [\"--skip-ppl\"]\n",
|
| 123 |
+
"if REQUIRE_FINETUNED_SLICE:\n",
|
| 124 |
+
" SUITE += [\"--require-finetuned-slice\"]\n",
|
| 125 |
+
"preview = BASE + [\"--repo\", REPOS[0], \"--show-config\"]\n",
|
| 126 |
+
"if TASKS:\n",
|
| 127 |
+
" preview += [\"--tasks\", *TASKS]\n",
|
| 128 |
+
"if not RUN_PPL:\n",
|
| 129 |
+
" preview += [\"--skip-ppl\"]\n",
|
| 130 |
+
"subprocess.run(preview, check=True)\n",
|
| 131 |
+
"subprocess.run(SUITE + [\"--plan\"], check=True)\n"
|
| 132 |
+
],
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"outputs": [],
|
| 135 |
+
"id": "cell-4"
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "markdown",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"Restore a prior output ZIP before running. It includes completed responses, RNG position and perplexity sequence progress. Resume with the same checkpoint SHA and effective config.\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"The optional Modal download preserves existing metrics and partial responses. BF16/32 and FP16/1 scores remain separate. Saved LoRA training states remain in Modal storage; this notebook does not resume paid training.\n"
|
| 144 |
+
],
|
| 145 |
+
"id": "cell-5"
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"if RESTORE_ZIP:\n",
|
| 152 |
+
" with zipfile.ZipFile(RESTORE_ZIP) as archive:\n",
|
| 153 |
+
" archive.extractall(WORK_DIR)\n",
|
| 154 |
+
"if IMPORT_MODAL_PROGRESS:\n",
|
| 155 |
+
" progress_zip = hf_hub_download(BUNDLE_REPO, \"modal_progress.zip\", repo_type=\"dataset\", revision=release, token=False)\n",
|
| 156 |
+
" restored = TEMP_DIR / \"restored_modal_progress\"\n",
|
| 157 |
+
" with zipfile.ZipFile(progress_zip) as archive:\n",
|
| 158 |
+
" archive.extractall(restored)\n",
|
| 159 |
+
" subprocess.run([sys.executable, str(EVAL_ROOT / \"import_modal_progress.py\"),\n",
|
| 160 |
+
" str(restored), \"--output\", str(OUTPUT_DIR)], check=True)\n"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": [],
|
| 164 |
+
"id": "cell-6"
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"cell_type": "code",
|
| 168 |
+
"metadata": {},
|
| 169 |
+
"source": [
|
| 170 |
+
"if RUN_FORWARD_SMOKE:\n",
|
| 171 |
+
" subprocess.run(BASE + [\"--repo\", REPOS[0], \"--smoke\",\n",
|
| 172 |
+
" \"--output\", str(WORK_DIR / \"forward_smoke\")], check=True)\n"
|
| 173 |
+
],
|
| 174 |
+
"execution_count": null,
|
| 175 |
+
"outputs": [],
|
| 176 |
+
"id": "cell-7"
|
| 177 |
+
},
|
| 178 |
+
{
|
| 179 |
+
"cell_type": "markdown",
|
| 180 |
+
"metadata": {},
|
| 181 |
+
"source": [
|
| 182 |
+
"Run the assignment below. Each likelihood response/generated answer saves locally, and perplexity saves after every sequence. At the time budget, the process returns with a pending-unit marker. Restore the ZIP in another session and rerun.\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"On Kaggle, use **Save Version \u2192 Save & Run All** for a background run. Save/download outputs before discarding an interactive session. For parallel sessions, change WORKER_INDEX and keep NUM_WORKERS fixed.\n"
|
| 185 |
+
],
|
| 186 |
+
"id": "cell-8"
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"import shutil\n",
|
| 193 |
+
"exit_code = None\n",
|
| 194 |
+
"try:\n",
|
| 195 |
+
" exit_code = subprocess.run(SUITE).returncode\n",
|
| 196 |
+
"finally:\n",
|
| 197 |
+
" archive_base = WORK_DIR / (\"evaluation_results_worker-\" + str(WORKER_INDEX))\n",
|
| 198 |
+
" archive_path = shutil.make_archive(str(archive_base), \"zip\", root_dir=WORK_DIR, base_dir=\"results\")\n",
|
| 199 |
+
" print(\"Saved resumable results:\", archive_path)\n",
|
| 200 |
+
" try:\n",
|
| 201 |
+
" from IPython.display import display, FileLink\n",
|
| 202 |
+
" display(FileLink(archive_path))\n",
|
| 203 |
+
" except ImportError:\n",
|
| 204 |
+
" pass\n",
|
| 205 |
+
"if exit_code:\n",
|
| 206 |
+
" raise RuntimeError(\"Evaluation failed; the ZIP retains committed progress. Check the preceding error.\")\n"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": [],
|
| 210 |
+
"id": "cell-9"
|
| 211 |
+
},
|
| 212 |
+
{
|
| 213 |
+
"cell_type": "markdown",
|
| 214 |
+
"metadata": {},
|
| 215 |
+
"source": [
|
| 216 |
+
"Download the ZIP from the Kaggle Output panel. Extract ZIPs from different workers into one directory before merging. The merger includes benchmark and perplexity metrics, rejects conflicting duplicates, and keeps config profiles separate.\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"For post-LoRA SliceGPT evaluation, choose the final fine-tuned repository and enable REQUIRE_FINETUNED_SLICE. Original SliceGPT repositories produce baseline results; they do not replace the unfinished WikiText-2 \u2192 C4 \u2192 Alpaca training.\n"
|
| 219 |
+
],
|
| 220 |
+
"id": "cell-10"
|
| 221 |
+
},
|
| 222 |
+
{
|
| 223 |
+
"cell_type": "code",
|
| 224 |
+
"metadata": {},
|
| 225 |
+
"source": [
|
| 226 |
+
"subprocess.run([sys.executable, str(EVAL_ROOT / \"runner.py\"), \"--merge\",\n",
|
| 227 |
+
" str(OUTPUT_DIR), \"--output\", str(WORK_DIR / \"merged_results.json\")], check=True)\n",
|
| 228 |
+
"print(\"Finished this session. No Modal jobs were started.\")\n"
|
| 229 |
+
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": [],
|
| 232 |
+
"id": "cell-11"
|
| 233 |
+
}
|
| 234 |
+
]
|
| 235 |
+
}
|
kaggle_slicegpt_lora.ipynb
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 5,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"kernelspec": {
|
| 6 |
+
"display_name": "Python 3",
|
| 7 |
+
"language": "python",
|
| 8 |
+
"name": "python3"
|
| 9 |
+
},
|
| 10 |
+
"language_info": {
|
| 11 |
+
"name": "python"
|
| 12 |
+
}
|
| 13 |
+
},
|
| 14 |
+
"cells": [
|
| 15 |
+
{
|
| 16 |
+
"cell_type": "markdown",
|
| 17 |
+
"metadata": {},
|
| 18 |
+
"source": [
|
| 19 |
+
"# Sequential SliceGPT LoRA on Kaggle\n",
|
| 20 |
+
"This is the same masked-diffusion LoRA procedure as the stopped Modal training: one adapter, WikiText-2 \u2192 C4 \u2192 Alpaca, pinned training datasets, rank 8/alpha 32, 4096 examples per stage, 2048 tokens, accumulation 4 and 3072 optimizer steps total.\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"Enable Internet and GPU. On T4 choose both GPUs; the trainer requires all weights on GPUs, with no CPU/disk training offload. FP16 is an explicit precision change; BF16 is available on supporting GPUs. Hyperparameters stay unchanged. Every 50 steps and stage boundary saves optimizer, adapter and RNG state. A session time budget saves and exits so another session can continue.\n"
|
| 23 |
+
],
|
| 24 |
+
"id": "cell-0"
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "code",
|
| 28 |
+
"metadata": {},
|
| 29 |
+
"source": [
|
| 30 |
+
"import sys, subprocess, os, json, hashlib, zipfile\n",
|
| 31 |
+
"from pathlib import Path\n",
|
| 32 |
+
"subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"huggingface-hub==0.36.0\"])\n",
|
| 33 |
+
"from huggingface_hub import HfApi, hf_hub_download\n",
|
| 34 |
+
"WORK_DIR = Path(\"/kaggle/working\") if Path(\"/kaggle\").exists() else Path.cwd()\n",
|
| 35 |
+
"TEMP_DIR = Path(\"/kaggle/temp\") if Path(\"/kaggle\").exists() else Path(\"/tmp\")\n",
|
| 36 |
+
"TEMP_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 37 |
+
"BUNDLE_REPO = \"vanshnawander/structured-diffusion-eval\"\n",
|
| 38 |
+
"release = HfApi(token=False).dataset_info(BUNDLE_REPO).sha\n",
|
| 39 |
+
"bundle = hf_hub_download(BUNDLE_REPO, \"portable_eval.zip\", repo_type=\"dataset\", revision=release, token=False)\n",
|
| 40 |
+
"manifest = json.loads(Path(hf_hub_download(BUNDLE_REPO, \"bundle_manifest.json\", repo_type=\"dataset\", revision=release, token=False)).read_text())\n",
|
| 41 |
+
"assert hashlib.sha256(Path(bundle).read_bytes()).hexdigest() == manifest[\"zip_sha256\"]\n",
|
| 42 |
+
"SOURCE_DIR = TEMP_DIR / \"structured_eval_source\"\n",
|
| 43 |
+
"SOURCE_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 44 |
+
"with zipfile.ZipFile(bundle) as archive:\n",
|
| 45 |
+
" archive.extractall(SOURCE_DIR)\n",
|
| 46 |
+
"EVAL_ROOT = SOURCE_DIR / \"portable_eval\"\n",
|
| 47 |
+
"subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-r\", str(EVAL_ROOT / \"requirements.txt\")])\n",
|
| 48 |
+
"print(\"Verified evaluation release:\", release)\n"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": [],
|
| 52 |
+
"id": "cell-1"
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"catalog = json.loads((EVAL_ROOT / \"models.json\").read_text())\n",
|
| 59 |
+
"slice_models = [row for row in catalog if row[\"method\"] == \"slicegpt\"]\n",
|
| 60 |
+
"for i, row in enumerate(slice_models):\n",
|
| 61 |
+
" print(i, row[\"repo_id\"])\n",
|
| 62 |
+
"MODEL_INDEX = 0\n",
|
| 63 |
+
"REPO = slice_models[MODEL_INDEX][\"repo_id\"]\n",
|
| 64 |
+
"DTYPE = \"float16\" # Explicit T4 profile; choose bfloat16 for matching supported hardware.\n",
|
| 65 |
+
"SESSION_HOURS = 8\n",
|
| 66 |
+
"TRAIN_OUTPUT = WORK_DIR / \"training_results\"\n",
|
| 67 |
+
"TRAIN_OUTPUT.mkdir(parents=True, exist_ok=True)\n",
|
| 68 |
+
"RESTORE_TRAINING_DIR = \"\" # Prior notebook's training_results directory under /kaggle/input.\n",
|
| 69 |
+
"UPLOAD_TO_HF = True # Final merged checkpoint is verified before public upload.\n",
|
| 70 |
+
"HF_NAMESPACE = \"vanshnawander\"\n",
|
| 71 |
+
"EVAL_AFTER_UPLOAD = False\n",
|
| 72 |
+
"RESTORE_MODAL_BF16 = False # True downloads the two saved BF16 LoRA recovery states.\n"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": [],
|
| 76 |
+
"id": "cell-2"
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"if RESTORE_TRAINING_DIR:\n",
|
| 83 |
+
" import shutil\n",
|
| 84 |
+
" shutil.copytree(RESTORE_TRAINING_DIR, TRAIN_OUTPUT, dirs_exist_ok=True)\n",
|
| 85 |
+
"if UPLOAD_TO_HF:\n",
|
| 86 |
+
" try:\n",
|
| 87 |
+
" from kaggle_secrets import UserSecretsClient\n",
|
| 88 |
+
" os.environ[\"HF_TOKEN\"] = UserSecretsClient().get_secret(\"HF_TOKEN\")\n",
|
| 89 |
+
" except ImportError:\n",
|
| 90 |
+
" from getpass import getpass\n",
|
| 91 |
+
" os.environ[\"HF_TOKEN\"] = getpass(\"Hugging Face write token: \")\n",
|
| 92 |
+
"TRAIN = [sys.executable, str(EVAL_ROOT / \"finetune_runner.py\"),\n",
|
| 93 |
+
" \"--repo\", REPO, \"--dtype\", DTYPE, \"--output\", str(TRAIN_OUTPUT),\n",
|
| 94 |
+
" \"--cache-dir\", str(TEMP_DIR / \"structured_training_hf\"),\n",
|
| 95 |
+
" \"--offload-dir\", str(TEMP_DIR / \"structured_training_offload\"),\n",
|
| 96 |
+
" \"--time-budget-seconds\", str(SESSION_HOURS * 3600), \"--namespace\", HF_NAMESPACE]\n",
|
| 97 |
+
"if UPLOAD_TO_HF:\n",
|
| 98 |
+
" TRAIN += [\"--upload\"]\n",
|
| 99 |
+
"subprocess.run(TRAIN + [\"--show-config\"], check=True)\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"if RESTORE_MODAL_BF16:\n",
|
| 102 |
+
" if DTYPE != \"bfloat16\":\n",
|
| 103 |
+
" raise ValueError(\"Saved Modal recovery uses BF16; FP16 must start a separate run.\")\n",
|
| 104 |
+
" recovery_zip = hf_hub_download(BUNDLE_REPO, \"modal_training_recovery.zip\",\n",
|
| 105 |
+
" repo_type=\"dataset\", revision=release, token=False)\n",
|
| 106 |
+
" recovery_root = TEMP_DIR / \"modal_training_recovery\"\n",
|
| 107 |
+
" with zipfile.ZipFile(recovery_zip) as archive:\n",
|
| 108 |
+
" archive.extractall(recovery_root)\n",
|
| 109 |
+
" job_name = REPO.split(\"/\")[-1].removeprefix(\"structured-\").removesuffix(\"-9fc515e82f313fab\")\n",
|
| 110 |
+
" recovery_job = recovery_root / \"training\" / job_name\n",
|
| 111 |
+
" if not (recovery_job / \"resume.json\").exists():\n",
|
| 112 |
+
" raise ValueError(\"This checkpoint had not started LoRA on Modal; no recovery exists.\")\n",
|
| 113 |
+
" TRAIN += [\"--restore-training-dir\", str(recovery_job)]\n"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": [],
|
| 117 |
+
"id": "cell-3"
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"subprocess.run(TRAIN, check=True)\n",
|
| 124 |
+
"resume_files = list(TRAIN_OUTPUT.glob(\"*/pipeline/training/*/resume.json\"))\n",
|
| 125 |
+
"for path in resume_files:\n",
|
| 126 |
+
" progress = json.loads(path.read_text())\n",
|
| 127 |
+
" print(path.parent.name, progress[\"global_step\"], \"/\", progress[\"total_steps\"], \"stage\", progress[\"stage\"])\n",
|
| 128 |
+
"uploaded_files = list(TRAIN_OUTPUT.glob(\"*/pipeline/training/*/uploaded.json\"))\n",
|
| 129 |
+
"print(\"Final uploads:\", [json.loads(path.read_text())[\"repo_id\"] for path in uploaded_files])\n"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": [],
|
| 133 |
+
"id": "cell-4"
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "markdown",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"If training returns with a continued marker, save the notebook output and attach its training_results folder to the next session. Set RESTORE_TRAINING_DIR and use the same model, precision and settings. Do not zip the original model weights: sources live in /kaggle/temp and can be downloaded again. After verified HF upload the merged payload and recovery tensors are removed from this run's output; adapters and metadata remain.\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"Saved Modal LoRA recovery states use BF16 and cannot be silently resumed with a different precision. They remain in the Modal volume. Training this notebook in FP16 starts a separate, clearly named run.\n"
|
| 142 |
+
],
|
| 143 |
+
"id": "cell-5"
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"if EVAL_AFTER_UPLOAD and uploaded_files:\n",
|
| 150 |
+
" # Each phase gets its own time budget; use a separate evaluation session if your current quota is low.\n",
|
| 151 |
+
" for marker in uploaded_files:\n",
|
| 152 |
+
" final_repo = json.loads(marker.read_text())[\"repo_id\"]\n",
|
| 153 |
+
" subprocess.run([sys.executable, str(EVAL_ROOT / \"run_suite.py\"), \"--repos\", final_repo,\n",
|
| 154 |
+
" \"--require-finetuned-slice\", \"--batch-size\", \"1\", \"--dtype\", \"auto\",\n",
|
| 155 |
+
" \"--output\", str(WORK_DIR / \"results\"), \"--cache-dir\", str(TEMP_DIR / \"structured_eval_hf\"),\n",
|
| 156 |
+
" \"--offload-dir\", str(TEMP_DIR / \"structured_eval_offload\"),\n",
|
| 157 |
+
" \"--time-budget-seconds\", \"3600\"], check=True)\n"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": [],
|
| 161 |
+
"id": "cell-6"
|
| 162 |
+
}
|
| 163 |
+
]
|
| 164 |
+
}
|
portable_eval.zip
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:89b29760ba2b7ab074568c6480277a7e859b9b80bd1f8dc3f0d9afba6977e123
|
| 3 |
+
size 66228
|
portable_lm_eval.ipynb
CHANGED
|
@@ -1,75 +1,134 @@
|
|
| 1 |
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
"cells": [
|
| 3 |
{
|
| 4 |
"cell_type": "markdown",
|
| 5 |
"metadata": {},
|
| 6 |
"source": [
|
| 7 |
-
"# Evaluate
|
| 8 |
-
"Enable
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
],
|
| 10 |
"id": "cell-0"
|
| 11 |
},
|
| 12 |
{
|
| 13 |
"cell_type": "code",
|
| 14 |
-
"execution_count": null,
|
| 15 |
"metadata": {},
|
| 16 |
-
"outputs": [],
|
| 17 |
"source": [
|
| 18 |
-
"import sys, subprocess\n",
|
| 19 |
-
"subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', 'huggingface-hub==0.36.0'])\n",
|
| 20 |
-
"from huggingface_hub import hf_hub_download\n",
|
| 21 |
"from pathlib import Path\n",
|
| 22 |
-
"
|
| 23 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
"with zipfile.ZipFile(bundle) as archive:\n",
|
| 25 |
-
" archive.extractall(
|
| 26 |
-
"EVAL_ROOT =
|
| 27 |
-
"subprocess.check_call([sys.executable,
|
|
|
|
| 28 |
],
|
|
|
|
|
|
|
| 29 |
"id": "cell-1"
|
| 30 |
},
|
| 31 |
{
|
| 32 |
"cell_type": "markdown",
|
| 33 |
"metadata": {},
|
| 34 |
"source": [
|
| 35 |
-
"If packages were already imported before installation, restart the
|
| 36 |
],
|
| 37 |
"id": "cell-2"
|
| 38 |
},
|
| 39 |
{
|
| 40 |
"cell_type": "code",
|
| 41 |
-
"execution_count": null,
|
| 42 |
"metadata": {},
|
| 43 |
-
"outputs": [],
|
| 44 |
"source": [
|
| 45 |
-
"
|
| 46 |
-
"
|
| 47 |
-
"
|
| 48 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
],
|
|
|
|
|
|
|
| 50 |
"id": "cell-3"
|
| 51 |
},
|
| 52 |
{
|
| 53 |
"cell_type": "code",
|
| 54 |
"metadata": {},
|
| 55 |
"source": [
|
| 56 |
-
"
|
| 57 |
-
"
|
| 58 |
-
"
|
| 59 |
-
"\n",
|
| 60 |
-
"
|
| 61 |
-
"
|
| 62 |
-
"
|
| 63 |
-
"
|
| 64 |
-
"\n",
|
| 65 |
-
"
|
| 66 |
-
"
|
| 67 |
-
"
|
| 68 |
-
"
|
| 69 |
-
"
|
| 70 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
"if not RUN_PPL:\n",
|
| 72 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
],
|
| 74 |
"execution_count": null,
|
| 75 |
"outputs": [],
|
|
@@ -79,7 +138,9 @@
|
|
| 79 |
"cell_type": "markdown",
|
| 80 |
"metadata": {},
|
| 81 |
"source": [
|
| 82 |
-
"
|
|
|
|
|
|
|
| 83 |
],
|
| 84 |
"id": "cell-5"
|
| 85 |
},
|
|
@@ -87,7 +148,16 @@
|
|
| 87 |
"cell_type": "code",
|
| 88 |
"metadata": {},
|
| 89 |
"source": [
|
| 90 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
],
|
| 92 |
"execution_count": null,
|
| 93 |
"outputs": [],
|
|
@@ -97,7 +167,9 @@
|
|
| 97 |
"cell_type": "code",
|
| 98 |
"metadata": {},
|
| 99 |
"source": [
|
| 100 |
-
"
|
|
|
|
|
|
|
| 101 |
],
|
| 102 |
"execution_count": null,
|
| 103 |
"outputs": [],
|
|
@@ -107,73 +179,57 @@
|
|
| 107 |
"cell_type": "markdown",
|
| 108 |
"metadata": {},
|
| 109 |
"source": [
|
| 110 |
-
"Run
|
|
|
|
|
|
|
| 111 |
],
|
| 112 |
"id": "cell-8"
|
| 113 |
},
|
| 114 |
-
{
|
| 115 |
-
"cell_type": "code",
|
| 116 |
-
"execution_count": null,
|
| 117 |
-
"metadata": {},
|
| 118 |
-
"outputs": [],
|
| 119 |
-
"source": [
|
| 120 |
-
"subprocess.run(COMMON + ['--tasks', 'piqa', '--limit', '2', '--skip-ppl'], check=True)\n"
|
| 121 |
-
],
|
| 122 |
-
"id": "cell-9"
|
| 123 |
-
},
|
| 124 |
{
|
| 125 |
"cell_type": "code",
|
| 126 |
"metadata": {},
|
| 127 |
"source": [
|
| 128 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
],
|
| 130 |
"execution_count": null,
|
| 131 |
"outputs": [],
|
| 132 |
-
"id": "cell-
|
| 133 |
},
|
| 134 |
{
|
| 135 |
"cell_type": "markdown",
|
| 136 |
"metadata": {},
|
| 137 |
"source": [
|
| 138 |
-
"
|
|
|
|
|
|
|
| 139 |
],
|
| 140 |
-
"id": "cell-
|
| 141 |
},
|
| 142 |
{
|
| 143 |
"cell_type": "code",
|
| 144 |
-
"execution_count": null,
|
| 145 |
"metadata": {},
|
| 146 |
-
"outputs": [],
|
| 147 |
"source": [
|
| 148 |
-
"
|
| 149 |
-
"
|
| 150 |
-
"
|
| 151 |
-
" from google.colab import files\n",
|
| 152 |
-
" files.download('evaluation_results.zip')\n",
|
| 153 |
-
"except ImportError:\n",
|
| 154 |
-
" print('Download evaluation_results.zip from the notebook output/files panel.')\n"
|
| 155 |
],
|
| 156 |
-
"
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
"cell_type": "markdown",
|
| 160 |
-
"metadata": {},
|
| 161 |
-
"source": [
|
| 162 |
-
"Keep the result ZIP before the session expires. Extract ZIPs from multiple workers into one results directory, then run runner.py --merge that_directory --output merged_results.json. It groups results by checkpoint revision and evaluation settings and rejects conflicting duplicate task scores."
|
| 163 |
-
],
|
| 164 |
-
"id": "cell-13"
|
| 165 |
-
}
|
| 166 |
-
],
|
| 167 |
-
"metadata": {
|
| 168 |
-
"kernelspec": {
|
| 169 |
-
"display_name": "Python 3",
|
| 170 |
-
"language": "python",
|
| 171 |
-
"name": "python3"
|
| 172 |
-
},
|
| 173 |
-
"language_info": {
|
| 174 |
-
"name": "python"
|
| 175 |
}
|
| 176 |
-
|
| 177 |
-
"nbformat": 4,
|
| 178 |
-
"nbformat_minor": 5
|
| 179 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 5,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"kernelspec": {
|
| 6 |
+
"display_name": "Python 3",
|
| 7 |
+
"language": "python",
|
| 8 |
+
"name": "python3"
|
| 9 |
+
},
|
| 10 |
+
"language_info": {
|
| 11 |
+
"name": "python"
|
| 12 |
+
}
|
| 13 |
+
},
|
| 14 |
"cells": [
|
| 15 |
{
|
| 16 |
"cell_type": "markdown",
|
| 17 |
"metadata": {},
|
| 18 |
"source": [
|
| 19 |
+
"# Evaluate pruned LLaDA/Dream on Kaggle or Colab\n",
|
| 20 |
+
"Enable **Internet** and a **GPU**. This notebook downloads public Hugging Face checkpoints and never calls Modal.\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"All seven benchmarks and both perplexity datasets are enabled. Choose one checkpoint per session, or shard the 27-checkpoint grid across sessions. Generation uses 256 steps, LLaDA length/block 1024, Dream length 256; likelihood uses MC 128. GSM8K retains five shots.\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"The kaggle profile explicitly uses MC mini-batch 1 and supported precision (FP16 on T4). MC sample count and generation settings stay unchanged, while precision/mini-batch differ from Modal BF16/32. Results stay separate by config. Use the shared profile on hardware that supports the original settings.\n",
|
| 25 |
+
"\nOriginal SliceGPT checkpoints require sequential LoRA first by default. Use the companion kaggle_slicegpt_lora.ipynb, then evaluate the final uploaded repo. Disable REQUIRE_FINETUNED_SLICE only to explicitly request baseline scores.\n"
|
| 26 |
],
|
| 27 |
"id": "cell-0"
|
| 28 |
},
|
| 29 |
{
|
| 30 |
"cell_type": "code",
|
|
|
|
| 31 |
"metadata": {},
|
|
|
|
| 32 |
"source": [
|
| 33 |
+
"import sys, subprocess, os, json, hashlib, zipfile\n",
|
|
|
|
|
|
|
| 34 |
"from pathlib import Path\n",
|
| 35 |
+
"subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"huggingface-hub==0.36.0\"])\n",
|
| 36 |
+
"from huggingface_hub import HfApi, hf_hub_download\n",
|
| 37 |
+
"WORK_DIR = Path(\"/kaggle/working\") if Path(\"/kaggle\").exists() else Path.cwd()\n",
|
| 38 |
+
"TEMP_DIR = Path(\"/kaggle/temp\") if Path(\"/kaggle\").exists() else Path(\"/tmp\")\n",
|
| 39 |
+
"TEMP_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 40 |
+
"BUNDLE_REPO = \"vanshnawander/structured-diffusion-eval\"\n",
|
| 41 |
+
"release = HfApi(token=False).dataset_info(BUNDLE_REPO).sha\n",
|
| 42 |
+
"bundle = hf_hub_download(BUNDLE_REPO, \"portable_eval.zip\", repo_type=\"dataset\", revision=release, token=False)\n",
|
| 43 |
+
"manifest = json.loads(Path(hf_hub_download(BUNDLE_REPO, \"bundle_manifest.json\", repo_type=\"dataset\", revision=release, token=False)).read_text())\n",
|
| 44 |
+
"assert hashlib.sha256(Path(bundle).read_bytes()).hexdigest() == manifest[\"zip_sha256\"]\n",
|
| 45 |
+
"SOURCE_DIR = TEMP_DIR / \"structured_eval_source\"\n",
|
| 46 |
+
"SOURCE_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 47 |
"with zipfile.ZipFile(bundle) as archive:\n",
|
| 48 |
+
" archive.extractall(SOURCE_DIR)\n",
|
| 49 |
+
"EVAL_ROOT = SOURCE_DIR / \"portable_eval\"\n",
|
| 50 |
+
"subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-r\", str(EVAL_ROOT / \"requirements.txt\")])\n",
|
| 51 |
+
"print(\"Verified evaluation release:\", release)\n"
|
| 52 |
],
|
| 53 |
+
"execution_count": null,
|
| 54 |
+
"outputs": [],
|
| 55 |
"id": "cell-1"
|
| 56 |
},
|
| 57 |
{
|
| 58 |
"cell_type": "markdown",
|
| 59 |
"metadata": {},
|
| 60 |
"source": [
|
| 61 |
+
"If packages were already imported before installation, restart the kernel and rerun setup. Existing PyTorch is kept when it meets the requirements. Model weights and offload files use /kaggle/temp; saved outputs contain only results and evaluation resume state.\n"
|
| 62 |
],
|
| 63 |
"id": "cell-2"
|
| 64 |
},
|
| 65 |
{
|
| 66 |
"cell_type": "code",
|
|
|
|
| 67 |
"metadata": {},
|
|
|
|
| 68 |
"source": [
|
| 69 |
+
"catalog = json.loads((EVAL_ROOT / \"models.json\").read_text())\n",
|
| 70 |
+
"for i, row in enumerate(catalog):\n",
|
| 71 |
+
" print(i, row[\"repo_id\"])\n",
|
| 72 |
+
"MODEL_INDEX = 0\n",
|
| 73 |
+
"REPOS = [catalog[MODEL_INDEX][\"repo_id\"]] # May also contain a final fine-tuned HF repository.\n",
|
| 74 |
+
"EVALUATE_ALL_MODELS = False # True selects all 27 original pruned checkpoints.\n",
|
| 75 |
+
"WORKER_INDEX = 0\n",
|
| 76 |
+
"NUM_WORKERS = 1 # Same count, distinct indices in parallel sessions.\n",
|
| 77 |
+
"PROFILE = \"kaggle\" # \"shared\" = authoritative BF16 / MC mini-batch 32.\n",
|
| 78 |
+
"SESSION_HOURS = 8 # End gracefully before the platform deadline.\n",
|
| 79 |
+
"TASKS = None # None = all seven tasks, including GSM8K.\n",
|
| 80 |
+
"RUN_PPL = True # WikiText-2 and C4, as in the shared config.\n",
|
| 81 |
+
"REQUIRE_FINETUNED_SLICE = True # True rejects original SliceGPT baselines.\n",
|
| 82 |
+
"RUN_FORWARD_SMOKE = True\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"# Original SliceGPT repositories are PRUNED BASELINES, not completed LoRA fine-tunes.\n",
|
| 85 |
+
"# No sequential LoRA fine-tune completed before Modal was stopped for the budget.\n",
|
| 86 |
+
"OUTPUT_DIR = WORK_DIR / \"results\"\n",
|
| 87 |
+
"CACHE_DIR = TEMP_DIR / \"structured_eval_hf\"\n",
|
| 88 |
+
"OFFLOAD_DIR = TEMP_DIR / \"structured_eval_offload\"\n",
|
| 89 |
+
"OUTPUT_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 90 |
+
"RESTORE_ZIP = \"\" # /kaggle/input/previous-results/evaluation_results_worker-0.zip\n",
|
| 91 |
+
"IMPORT_MODAL_PROGRESS = False # BF16/32 scores are not reused by the FP16/1 profile.\n"
|
| 92 |
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": [],
|
| 95 |
"id": "cell-3"
|
| 96 |
},
|
| 97 |
{
|
| 98 |
"cell_type": "code",
|
| 99 |
"metadata": {},
|
| 100 |
"source": [
|
| 101 |
+
"import torch\n",
|
| 102 |
+
"print(\"GPUs:\", [(i, torch.cuda.get_device_name(i)) for i in range(torch.cuda.device_count())])\n",
|
| 103 |
+
"if not torch.cuda.is_available():\n",
|
| 104 |
+
" raise RuntimeError(\"Enable a GPU runtime in Kaggle/Colab settings.\")\n",
|
| 105 |
+
"assert PROFILE in {\"shared\", \"kaggle\"}\n",
|
| 106 |
+
"RESOURCE_ARGS = [] if PROFILE == \"shared\" else [\"--batch-size\", \"1\", \"--dtype\", \"auto\"]\n",
|
| 107 |
+
"if PROFILE == \"shared\" and not torch.cuda.is_bf16_supported():\n",
|
| 108 |
+
" raise RuntimeError(\"This GPU does not support BF16. Choose PROFILE='kaggle' explicitly.\")\n",
|
| 109 |
+
"BASE = [sys.executable, str(EVAL_ROOT / \"runner.py\"), \"--device\", \"cuda\",\n",
|
| 110 |
+
" \"--device-map\", \"auto\", \"--gpu-memory-ratio\", \"0.65\",\n",
|
| 111 |
+
" \"--cache-dir\", str(CACHE_DIR), \"--offload-dir\", str(OFFLOAD_DIR)] + RESOURCE_ARGS\n",
|
| 112 |
+
"SUITE = [sys.executable, str(EVAL_ROOT / \"run_suite.py\"),\n",
|
| 113 |
+
" \"--worker-index\", str(WORKER_INDEX), \"--num-workers\", str(NUM_WORKERS),\n",
|
| 114 |
+
" \"--output\", str(OUTPUT_DIR), \"--cache-dir\", str(CACHE_DIR),\n",
|
| 115 |
+
" \"--offload-dir\", str(OFFLOAD_DIR), \"--time-budget-seconds\", str(SESSION_HOURS * 3600),\n",
|
| 116 |
+
" \"--request-chunk-size\", \"1\"] + RESOURCE_ARGS\n",
|
| 117 |
+
"if not EVALUATE_ALL_MODELS:\n",
|
| 118 |
+
" SUITE += [\"--repos\", *REPOS]\n",
|
| 119 |
+
"if TASKS:\n",
|
| 120 |
+
" SUITE += [\"--tasks\", *TASKS]\n",
|
| 121 |
"if not RUN_PPL:\n",
|
| 122 |
+
" SUITE += [\"--skip-ppl\"]\n",
|
| 123 |
+
"if REQUIRE_FINETUNED_SLICE:\n",
|
| 124 |
+
" SUITE += [\"--require-finetuned-slice\"]\n",
|
| 125 |
+
"preview = BASE + [\"--repo\", REPOS[0], \"--show-config\"]\n",
|
| 126 |
+
"if TASKS:\n",
|
| 127 |
+
" preview += [\"--tasks\", *TASKS]\n",
|
| 128 |
+
"if not RUN_PPL:\n",
|
| 129 |
+
" preview += [\"--skip-ppl\"]\n",
|
| 130 |
+
"subprocess.run(preview, check=True)\n",
|
| 131 |
+
"subprocess.run(SUITE + [\"--plan\"], check=True)\n"
|
| 132 |
],
|
| 133 |
"execution_count": null,
|
| 134 |
"outputs": [],
|
|
|
|
| 138 |
"cell_type": "markdown",
|
| 139 |
"metadata": {},
|
| 140 |
"source": [
|
| 141 |
+
"Restore a prior output ZIP before running. It includes completed responses, RNG position and perplexity sequence progress. Resume with the same checkpoint SHA and effective config.\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"The optional Modal download preserves existing metrics and partial responses. BF16/32 and FP16/1 scores remain separate. Saved LoRA training states remain in Modal storage; this notebook does not resume paid training.\n"
|
| 144 |
],
|
| 145 |
"id": "cell-5"
|
| 146 |
},
|
|
|
|
| 148 |
"cell_type": "code",
|
| 149 |
"metadata": {},
|
| 150 |
"source": [
|
| 151 |
+
"if RESTORE_ZIP:\n",
|
| 152 |
+
" with zipfile.ZipFile(RESTORE_ZIP) as archive:\n",
|
| 153 |
+
" archive.extractall(WORK_DIR)\n",
|
| 154 |
+
"if IMPORT_MODAL_PROGRESS:\n",
|
| 155 |
+
" progress_zip = hf_hub_download(BUNDLE_REPO, \"modal_progress.zip\", repo_type=\"dataset\", revision=release, token=False)\n",
|
| 156 |
+
" restored = TEMP_DIR / \"restored_modal_progress\"\n",
|
| 157 |
+
" with zipfile.ZipFile(progress_zip) as archive:\n",
|
| 158 |
+
" archive.extractall(restored)\n",
|
| 159 |
+
" subprocess.run([sys.executable, str(EVAL_ROOT / \"import_modal_progress.py\"),\n",
|
| 160 |
+
" str(restored), \"--output\", str(OUTPUT_DIR)], check=True)\n"
|
| 161 |
],
|
| 162 |
"execution_count": null,
|
| 163 |
"outputs": [],
|
|
|
|
| 167 |
"cell_type": "code",
|
| 168 |
"metadata": {},
|
| 169 |
"source": [
|
| 170 |
+
"if RUN_FORWARD_SMOKE:\n",
|
| 171 |
+
" subprocess.run(BASE + [\"--repo\", REPOS[0], \"--smoke\",\n",
|
| 172 |
+
" \"--output\", str(WORK_DIR / \"forward_smoke\")], check=True)\n"
|
| 173 |
],
|
| 174 |
"execution_count": null,
|
| 175 |
"outputs": [],
|
|
|
|
| 179 |
"cell_type": "markdown",
|
| 180 |
"metadata": {},
|
| 181 |
"source": [
|
| 182 |
+
"Run the assignment below. Each likelihood response/generated answer saves locally, and perplexity saves after every sequence. At the time budget, the process returns with a pending-unit marker. Restore the ZIP in another session and rerun.\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"On Kaggle, use **Save Version \u2192 Save & Run All** for a background run. Save/download outputs before discarding an interactive session. For parallel sessions, change WORKER_INDEX and keep NUM_WORKERS fixed.\n"
|
| 185 |
],
|
| 186 |
"id": "cell-8"
|
| 187 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
{
|
| 189 |
"cell_type": "code",
|
| 190 |
"metadata": {},
|
| 191 |
"source": [
|
| 192 |
+
"import shutil\n",
|
| 193 |
+
"exit_code = None\n",
|
| 194 |
+
"try:\n",
|
| 195 |
+
" exit_code = subprocess.run(SUITE).returncode\n",
|
| 196 |
+
"finally:\n",
|
| 197 |
+
" archive_base = WORK_DIR / (\"evaluation_results_worker-\" + str(WORKER_INDEX))\n",
|
| 198 |
+
" archive_path = shutil.make_archive(str(archive_base), \"zip\", root_dir=WORK_DIR, base_dir=\"results\")\n",
|
| 199 |
+
" print(\"Saved resumable results:\", archive_path)\n",
|
| 200 |
+
" try:\n",
|
| 201 |
+
" from IPython.display import display, FileLink\n",
|
| 202 |
+
" display(FileLink(archive_path))\n",
|
| 203 |
+
" except ImportError:\n",
|
| 204 |
+
" pass\n",
|
| 205 |
+
"if exit_code:\n",
|
| 206 |
+
" raise RuntimeError(\"Evaluation failed; the ZIP retains committed progress. Check the preceding error.\")\n"
|
| 207 |
],
|
| 208 |
"execution_count": null,
|
| 209 |
"outputs": [],
|
| 210 |
+
"id": "cell-9"
|
| 211 |
},
|
| 212 |
{
|
| 213 |
"cell_type": "markdown",
|
| 214 |
"metadata": {},
|
| 215 |
"source": [
|
| 216 |
+
"Download the ZIP from the Kaggle Output panel. Extract ZIPs from different workers into one directory before merging. The merger includes benchmark and perplexity metrics, rejects conflicting duplicates, and keeps config profiles separate.\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"For post-LoRA SliceGPT evaluation, choose the final fine-tuned repository and enable REQUIRE_FINETUNED_SLICE. Original SliceGPT repositories produce baseline results; they do not replace the unfinished WikiText-2 \u2192 C4 \u2192 Alpaca training.\n"
|
| 219 |
],
|
| 220 |
+
"id": "cell-10"
|
| 221 |
},
|
| 222 |
{
|
| 223 |
"cell_type": "code",
|
|
|
|
| 224 |
"metadata": {},
|
|
|
|
| 225 |
"source": [
|
| 226 |
+
"subprocess.run([sys.executable, str(EVAL_ROOT / \"runner.py\"), \"--merge\",\n",
|
| 227 |
+
" str(OUTPUT_DIR), \"--output\", str(WORK_DIR / \"merged_results.json\")], check=True)\n",
|
| 228 |
+
"print(\"Finished this session. No Modal jobs were started.\")\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": [],
|
| 232 |
+
"id": "cell-11"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
}
|
| 234 |
+
]
|
|
|
|
|
|
|
| 235 |
}
|
run_suite.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run disjoint checkpoint/task assignments on Kaggle, Colab, or another GPU."""
|
| 2 |
+
import argparse
|
| 3 |
+
from dataclasses import asdict
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
from runner import DiffusionEvalConfig, evaluation_units, write_json
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def assignments(catalog, worker_index=0, num_workers=1, tasks=None, run_ppl=True):
|
| 15 |
+
if num_workers < 1 or not 0 <= worker_index < num_workers:
|
| 16 |
+
raise ValueError("Require 0 <= worker-index < num-workers")
|
| 17 |
+
cfg = DiffusionEvalConfig()
|
| 18 |
+
cfg.skip_ppl = not run_ppl
|
| 19 |
+
work = []
|
| 20 |
+
for item in catalog:
|
| 21 |
+
if not item.get("ready", True):
|
| 22 |
+
continue
|
| 23 |
+
family = "dream" if item.get("model", "").startswith("Dream-org/") or "structured-dream-" in item["repo_id"] else "llada"
|
| 24 |
+
work.extend({"repo_id": item["repo_id"], "revision": item.get("revision"),
|
| 25 |
+
"unit": unit, "family": family}
|
| 26 |
+
for unit in evaluation_units(cfg, family, selected_tasks=tasks))
|
| 27 |
+
return work[worker_index::num_workers]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def main():
|
| 31 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 32 |
+
parser.add_argument("--catalog", default=str(Path(__file__).with_name("models.json")))
|
| 33 |
+
parser.add_argument("--repos", nargs="+", help="Select one or more original or fine-tuned public repositories")
|
| 34 |
+
parser.add_argument("--worker-index", type=int, default=0)
|
| 35 |
+
parser.add_argument("--num-workers", type=int, default=1)
|
| 36 |
+
parser.add_argument("--tasks", nargs="+")
|
| 37 |
+
parser.add_argument("--skip-ppl", action="store_true")
|
| 38 |
+
parser.add_argument("--plan", action="store_true")
|
| 39 |
+
parser.add_argument("--batch-size", type=int)
|
| 40 |
+
parser.add_argument("--dtype", choices=["auto", "bfloat16", "float16", "float32"])
|
| 41 |
+
parser.add_argument("--device", default="cuda")
|
| 42 |
+
parser.add_argument("--device-map", choices=["auto", "single"], default="auto")
|
| 43 |
+
parser.add_argument("--gpu-memory-ratio", type=float, default=.65)
|
| 44 |
+
parser.add_argument("--output", default="results")
|
| 45 |
+
parser.add_argument("--cache-dir", default=".eval_cache")
|
| 46 |
+
parser.add_argument("--offload-dir", default=".eval_offload")
|
| 47 |
+
parser.add_argument("--time-budget-seconds", type=float, default=8*3600)
|
| 48 |
+
parser.add_argument("--request-chunk-size", type=int, default=1)
|
| 49 |
+
parser.add_argument("--require-finetuned-slice", action="store_true")
|
| 50 |
+
args = parser.parse_args()
|
| 51 |
+
catalog = json.loads(Path(args.catalog).read_text())
|
| 52 |
+
if args.repos:
|
| 53 |
+
selected = {r["repo_id"]: r for r in catalog}
|
| 54 |
+
catalog = [selected.get(repo, {"repo_id": repo, "ready": True}) for repo in args.repos]
|
| 55 |
+
work = assignments(catalog, args.worker_index, args.num_workers, args.tasks, not args.skip_ppl)
|
| 56 |
+
if args.plan:
|
| 57 |
+
print(json.dumps({"assignments": work, "units": len(work),
|
| 58 |
+
"shared_config": asdict(DiffusionEvalConfig())}, indent=2))
|
| 59 |
+
return
|
| 60 |
+
deadline = time.monotonic() + args.time_budget_seconds
|
| 61 |
+
grouped = {}
|
| 62 |
+
for item in work:
|
| 63 |
+
grouped.setdefault((item["repo_id"], item["revision"]), []).append(item["unit"])
|
| 64 |
+
status = {"worker_index": args.worker_index, "num_workers": args.num_workers,
|
| 65 |
+
"assigned_units": len(work), "models_attempted": [], "errors": []}
|
| 66 |
+
runner = str(Path(__file__).with_name("runner.py"))
|
| 67 |
+
for (repo, revision), units in grouped.items():
|
| 68 |
+
remaining = deadline - time.monotonic()
|
| 69 |
+
if remaining <= 0:
|
| 70 |
+
break
|
| 71 |
+
cmd = [sys.executable, runner, "--repo", repo, "--units", *units,
|
| 72 |
+
"--device", args.device, "--device-map", args.device_map,
|
| 73 |
+
"--gpu-memory-ratio", str(args.gpu_memory_ratio), "--output", args.output,
|
| 74 |
+
"--cache-dir", args.cache_dir, "--offload-dir", args.offload_dir,
|
| 75 |
+
"--time-budget-seconds", str(remaining), "--request-chunk-size", str(args.request_chunk_size)]
|
| 76 |
+
if revision:
|
| 77 |
+
cmd += ["--revision", revision]
|
| 78 |
+
if args.batch_size is not None:
|
| 79 |
+
cmd += ["--batch-size", str(args.batch_size)]
|
| 80 |
+
if args.dtype:
|
| 81 |
+
cmd += ["--dtype", args.dtype]
|
| 82 |
+
if args.skip_ppl:
|
| 83 |
+
cmd += ["--skip-ppl"]
|
| 84 |
+
if args.require_finetuned_slice:
|
| 85 |
+
cmd += ["--require-finetuned-slice"]
|
| 86 |
+
status["models_attempted"].append(repo)
|
| 87 |
+
write_json(Path(args.output) / ("worker_" + str(args.worker_index) + "_status.json"), status)
|
| 88 |
+
result = subprocess.run(cmd)
|
| 89 |
+
if result.returncode:
|
| 90 |
+
status["errors"].append({"repo_id": repo, "exit_code": result.returncode})
|
| 91 |
+
break
|
| 92 |
+
write_json(Path(args.output) / ("worker_" + str(args.worker_index) + "_status.json"), status)
|
| 93 |
+
if status["errors"]:
|
| 94 |
+
raise SystemExit(status["errors"][-1]["exit_code"])
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if __name__ == "__main__":
|
| 98 |
+
main()
|
runner.py
CHANGED
|
@@ -9,6 +9,7 @@ import os
|
|
| 9 |
from pathlib import Path
|
| 10 |
import random
|
| 11 |
import sys
|
|
|
|
| 12 |
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 13 |
from diffusion_eval_and_vis.config import DiffusionEvalConfig
|
| 14 |
|
|
@@ -20,7 +21,20 @@ def write_json(path, value):
|
|
| 20 |
path = Path(path)
|
| 21 |
path.parent.mkdir(parents=True, exist_ok=True)
|
| 22 |
temporary = path.with_suffix(path.suffix + ".tmp")
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
temporary.replace(path)
|
| 25 |
|
| 26 |
|
|
@@ -225,12 +239,19 @@ def merge_results(root, destination):
|
|
| 225 |
groups = {}
|
| 226 |
for path in Path(root).rglob("*.json"):
|
| 227 |
value = json.loads(path.read_text())
|
| 228 |
-
if value.get("kind")
|
| 229 |
continue
|
| 230 |
metadata = value["metadata"]
|
| 231 |
key = (metadata["repo_id"], metadata["revision"],
|
| 232 |
json.dumps(metadata["eval_config"], sort_keys=True))
|
| 233 |
-
group = groups.setdefault(key, {"metadata": metadata, "results": {}, "tasks": []})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
for task, metrics in value["results"]["results"].items():
|
| 235 |
if task in group["results"] and group["results"][task] != metrics:
|
| 236 |
raise ValueError("Conflicting duplicate task results: " + task)
|
|
@@ -241,6 +262,84 @@ def merge_results(root, destination):
|
|
| 241 |
return len(groups)
|
| 242 |
|
| 243 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
def main():
|
| 245 |
parser = argparse.ArgumentParser(description=__doc__)
|
| 246 |
parser.add_argument("--repo")
|
|
@@ -252,11 +351,15 @@ def main():
|
|
| 252 |
parser.add_argument("--owner", default=DEFAULT_OWNER)
|
| 253 |
parser.add_argument("--run", default=DEFAULT_RUN)
|
| 254 |
parser.add_argument("--tasks", nargs="+")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
parser.add_argument("--batch-size", type=int)
|
| 256 |
parser.add_argument("--mc-num", type=int)
|
| 257 |
parser.add_argument("--limit", type=int)
|
| 258 |
parser.add_argument("--dtype", choices=["auto", "bfloat16", "float16", "float32"])
|
| 259 |
-
parser.add_argument("--device", default="cuda
|
| 260 |
parser.add_argument("--device-map", choices=["auto", "single"], default="auto")
|
| 261 |
parser.add_argument("--gpu-memory-ratio", type=float, default=0.65)
|
| 262 |
parser.add_argument("--cpu-memory-gib", type=float)
|
|
@@ -279,6 +382,9 @@ def main():
|
|
| 279 |
parser.error("Supply --repo or --checkpoint")
|
| 280 |
import torch
|
| 281 |
from huggingface_hub import HfApi, snapshot_download
|
|
|
|
|
|
|
|
|
|
| 282 |
cfg = DiffusionEvalConfig()
|
| 283 |
cfg.device = args.device
|
| 284 |
for key in ("batch_size", "mc_num", "limit"):
|
|
@@ -290,16 +396,18 @@ def main():
|
|
| 290 |
cfg.dtype = "bfloat16" if cfg.device.startswith("cuda") and torch.cuda.is_bf16_supported() else "float16" if cfg.device.startswith("cuda") else "float32"
|
| 291 |
if cfg.batch_size <= 0 or cfg.mc_num <= 0 or cfg.mc_num % cfg.batch_size:
|
| 292 |
raise ValueError("batch-size must be positive and divide mc-num")
|
| 293 |
-
if cfg.device.startswith("cuda") and not torch.cuda.is_available():
|
| 294 |
raise RuntimeError("Enable a GPU runtime or pass --device cpu")
|
| 295 |
-
if cfg.dtype == "bfloat16" and cfg.device.startswith("cuda") and not torch.cuda.is_bf16_supported():
|
| 296 |
raise RuntimeError("This GPU needs --dtype auto or --dtype float16; the override is recorded in results")
|
| 297 |
if args.show_config:
|
| 298 |
family = args.family or ("dream" if "structured-dream-" in (args.repo or "") else "llada")
|
| 299 |
tasks = args.tasks or (cfg.dream_tasks or cfg.llada_tasks if family == "dream" else cfg.llada_tasks)
|
| 300 |
print(json.dumps({"family": family, "eval_config": asdict(cfg),
|
| 301 |
"adapter_parameters": adapter_parameters(cfg, family),
|
| 302 |
-
"worker_tasks":
|
|
|
|
|
|
|
| 303 |
"perplexity_enabled": not cfg.skip_ppl,
|
| 304 |
"note": "llada_generation_* are separate helper defaults; the benchmark uses llada_steps/llada_gen_length/llada_block_length."}, indent=2))
|
| 305 |
return
|
|
@@ -312,9 +420,12 @@ def main():
|
|
| 312 |
checkpoint = snapshot_download(args.repo, revision=revision, token=token, cache_dir=args.cache_dir)
|
| 313 |
root = Path(checkpoint)
|
| 314 |
saved = json.loads((root / "checkpoint_manifest.json").read_text()) if (root / "checkpoint_manifest.json").exists() else None
|
| 315 |
-
|
|
|
|
| 316 |
if (root / "slicegpt_metadata.json").exists():
|
| 317 |
family = json.loads((root / "slicegpt_metadata.json").read_text())["family"]
|
|
|
|
|
|
|
| 318 |
seed_all(cfg.seed)
|
| 319 |
model, tokenizer = load_checkpoint(checkpoint, cfg, args.device_map, args.gpu_memory_ratio,
|
| 320 |
args.cpu_memory_gib, str(Path(args.offload_dir) / f"worker-{args.worker_index}"))
|
|
@@ -322,7 +433,9 @@ def main():
|
|
| 322 |
"family": family, "torch_version": torch.__version__,
|
| 323 |
"device_map": getattr(model, "hf_device_map", {"": cfg.device})}
|
| 324 |
label = (args.repo or root.name).split("/")[-1]
|
| 325 |
-
|
|
|
|
|
|
|
| 326 |
if args.smoke:
|
| 327 |
inputs = tokenizer("The quick brown fox.", return_tensors="pt").input_ids.to(cfg.device)
|
| 328 |
with torch.no_grad():
|
|
@@ -332,48 +445,12 @@ def main():
|
|
| 332 |
write_json(output / "smoke.json", {"complete": True, "metadata": metadata, "shape": list(logits.shape)})
|
| 333 |
print(json.dumps({"smoke_passed": True, "output": str(output), "metadata": metadata}, default=str))
|
| 334 |
return
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
for task in tasks:
|
| 342 |
-
path = output / (task + ".json")
|
| 343 |
-
if path.exists():
|
| 344 |
-
old = json.loads(path.read_text())
|
| 345 |
-
if old.get("signature") == signature and old.get("complete"):
|
| 346 |
-
print("Already completed:", task, flush=True)
|
| 347 |
-
continue
|
| 348 |
-
def seeded_evaluate(**kw):
|
| 349 |
-
return lm_eval.simple_evaluate(**kw, random_seed=cfg.seed, numpy_random_seed=cfg.seed,
|
| 350 |
-
torch_random_seed=cfg.seed, fewshot_random_seed=cfg.seed)
|
| 351 |
-
result = evaluate_tasks(adapter, [task], limit=cfg.limit, simple_evaluate=seeded_evaluate)
|
| 352 |
-
if task not in result.get("results", {}):
|
| 353 |
-
raise ValueError("lm-eval returned no result for " + task)
|
| 354 |
-
write_json(path, {"kind": "lm_eval_task", "complete": True, "signature": signature,
|
| 355 |
-
"metadata": metadata, "results": result})
|
| 356 |
-
print("Saved:", path, flush=True)
|
| 357 |
-
# Task workers partition PPL datasets as well; no duplicate PPL work.
|
| 358 |
-
if not cfg.skip_ppl:
|
| 359 |
-
if family == "dream":
|
| 360 |
-
from diffusion_eval_and_vis.eval_dream import evaluate_perplexity_dream as ppl
|
| 361 |
-
length = cfg.dream_ppl_seq_len
|
| 362 |
-
else:
|
| 363 |
-
from diffusion_eval_and_vis.eval_diffusion import evaluate_perplexity as ppl
|
| 364 |
-
length = cfg.llada_ppl_seq_len
|
| 365 |
-
for dataset in split_tasks(cfg.ppl_datasets, args.worker_index, args.num_workers):
|
| 366 |
-
kw = dict(model=model, tokenizer=tokenizer, dataset=dataset, seq_len=length,
|
| 367 |
-
device=cfg.device, mc_num=cfg.mc_num, mc_batch_size=cfg.batch_size)
|
| 368 |
-
if family == "dream":
|
| 369 |
-
kw["sampling_eps"] = cfg.sampling_eps
|
| 370 |
-
value = float(ppl(**kw))
|
| 371 |
-
import math
|
| 372 |
-
if not math.isfinite(value):
|
| 373 |
-
raise ValueError("Non-finite perplexity")
|
| 374 |
-
write_json(output / ("perplexity_" + dataset + ".json"),
|
| 375 |
-
{"kind": "perplexity", "complete": True, "metadata": metadata, "value": value})
|
| 376 |
-
del adapter, model, tokenizer
|
| 377 |
gc.collect()
|
| 378 |
if torch.cuda.is_available():
|
| 379 |
torch.cuda.empty_cache()
|
|
|
|
| 9 |
from pathlib import Path
|
| 10 |
import random
|
| 11 |
import sys
|
| 12 |
+
import time
|
| 13 |
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 14 |
from diffusion_eval_and_vis.config import DiffusionEvalConfig
|
| 15 |
|
|
|
|
| 21 |
path = Path(path)
|
| 22 |
path.parent.mkdir(parents=True, exist_ok=True)
|
| 23 |
temporary = path.with_suffix(path.suffix + ".tmp")
|
| 24 |
+
def clean(value):
|
| 25 |
+
import math
|
| 26 |
+
if isinstance(value, dict):
|
| 27 |
+
return {str(k): clean(v) for k, v in value.items()}
|
| 28 |
+
if isinstance(value, (list, tuple)):
|
| 29 |
+
return [clean(v) for v in value]
|
| 30 |
+
if hasattr(value, "tolist"):
|
| 31 |
+
return clean(value.tolist())
|
| 32 |
+
if isinstance(value, float) and not math.isfinite(value):
|
| 33 |
+
return None
|
| 34 |
+
if value is None or isinstance(value, (str, int, float, bool)):
|
| 35 |
+
return value
|
| 36 |
+
return str(value)
|
| 37 |
+
temporary.write_text(json.dumps(clean(value), indent=2, allow_nan=False))
|
| 38 |
temporary.replace(path)
|
| 39 |
|
| 40 |
|
|
|
|
| 239 |
groups = {}
|
| 240 |
for path in Path(root).rglob("*.json"):
|
| 241 |
value = json.loads(path.read_text())
|
| 242 |
+
if value.get("kind") not in {"lm_eval_task", "perplexity"} or not value.get("complete"):
|
| 243 |
continue
|
| 244 |
metadata = value["metadata"]
|
| 245 |
key = (metadata["repo_id"], metadata["revision"],
|
| 246 |
json.dumps(metadata["eval_config"], sort_keys=True))
|
| 247 |
+
group = groups.setdefault(key, {"metadata": metadata, "results": {}, "tasks": [], "perplexities": {}})
|
| 248 |
+
if value["kind"] == "perplexity":
|
| 249 |
+
dataset = value.get("results", {}).get("dataset") or path.stem.removeprefix("perplexity_").removeprefix("ppl_")
|
| 250 |
+
number = value.get("value", value.get("results", {}).get("perplexity"))
|
| 251 |
+
if dataset in group["perplexities"] and group["perplexities"][dataset] != number:
|
| 252 |
+
raise ValueError("Conflicting duplicate perplexity: " + dataset)
|
| 253 |
+
group["perplexities"][dataset] = number
|
| 254 |
+
continue
|
| 255 |
for task, metrics in value["results"]["results"].items():
|
| 256 |
if task in group["results"] and group["results"][task] != metrics:
|
| 257 |
raise ValueError("Conflicting duplicate task results: " + task)
|
|
|
|
| 262 |
return len(groups)
|
| 263 |
|
| 264 |
|
| 265 |
+
|
| 266 |
+
def evaluation_units(cfg, family, selected_tasks=None, selected_units=None, worker_index=0, num_workers=1):
|
| 267 |
+
tasks = selected_tasks or ((cfg.dream_tasks or cfg.llada_tasks) if family == "dream" else cfg.llada_tasks)
|
| 268 |
+
allowed = ["task:" + task for task in tasks] + ([] if cfg.skip_ppl else ["ppl:" + dataset for dataset in cfg.ppl_datasets])
|
| 269 |
+
units = list(selected_units) if selected_units is not None else allowed
|
| 270 |
+
if len(set(units)) != len(units) or not set(units) <= set(allowed):
|
| 271 |
+
raise ValueError("Unknown or duplicate evaluation units")
|
| 272 |
+
return split_tasks(units, worker_index, num_workers)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def matching_result(value, metadata):
|
| 276 |
+
old = value.get("metadata", {})
|
| 277 |
+
return bool(value.get("complete") and old.get("repo_id") == metadata["repo_id"]
|
| 278 |
+
and old.get("revision") == metadata["revision"] and old.get("eval_config") == metadata["eval_config"])
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def run_units(model, tokenizer, cfg, family, checkpoint, metadata, output, units, deadline=None, request_chunk_size=32):
|
| 282 |
+
from diffusion_eval_and_vis.resume import attach_response_cache, EvaluationContinuation
|
| 283 |
+
from diffusion_eval_and_vis.lm_eval_utils import evaluate_tasks
|
| 284 |
+
import lm_eval
|
| 285 |
+
output = Path(output)
|
| 286 |
+
completed = []
|
| 287 |
+
for unit in units:
|
| 288 |
+
path = output / (unit.split(":", 1)[1] + ".json" if unit.startswith("task:") else
|
| 289 |
+
"perplexity_" + unit.split(":", 1)[1] + ".json")
|
| 290 |
+
if path.exists() and matching_result(json.loads(path.read_text()), metadata):
|
| 291 |
+
print("Already completed:", unit, flush=True)
|
| 292 |
+
completed.append(unit)
|
| 293 |
+
continue
|
| 294 |
+
if deadline is not None and time.monotonic() >= deadline:
|
| 295 |
+
return {"complete": False, "completed_units": completed, "pending_unit": unit}
|
| 296 |
+
signature = {"repo_id": metadata["repo_id"], "revision": metadata["revision"],
|
| 297 |
+
"eval_config": metadata["eval_config"], "unit": unit, "smoke": False}
|
| 298 |
+
seed_all(cfg.seed)
|
| 299 |
+
try:
|
| 300 |
+
if unit.startswith("task:"):
|
| 301 |
+
task = unit.split(":", 1)[1]
|
| 302 |
+
adapter = make_adapter(model, tokenizer, cfg, family, checkpoint)
|
| 303 |
+
attach_response_cache(adapter, output / (task + "_responses"), signature, lambda: None,
|
| 304 |
+
seconds=float("inf"), progress=output / (task + "_progress.json"),
|
| 305 |
+
deadline=deadline, request_chunk_size=request_chunk_size)
|
| 306 |
+
def seeded_evaluate(**kw):
|
| 307 |
+
return lm_eval.simple_evaluate(**kw, random_seed=cfg.seed, numpy_random_seed=cfg.seed,
|
| 308 |
+
torch_random_seed=cfg.seed, fewshot_random_seed=cfg.seed)
|
| 309 |
+
result = evaluate_tasks(adapter, [task], limit=cfg.limit, simple_evaluate=seeded_evaluate)
|
| 310 |
+
if task not in result.get("results", {}):
|
| 311 |
+
raise ValueError("lm-eval returned no result for " + task)
|
| 312 |
+
record = {"kind": "lm_eval_task", "complete": True, "metadata": metadata, "results": result}
|
| 313 |
+
del adapter
|
| 314 |
+
else:
|
| 315 |
+
dataset = unit.split(":", 1)[1]
|
| 316 |
+
if family == "dream":
|
| 317 |
+
from diffusion_eval_and_vis.eval_dream import evaluate_perplexity_dream as ppl
|
| 318 |
+
length = cfg.dream_ppl_seq_len
|
| 319 |
+
else:
|
| 320 |
+
from diffusion_eval_and_vis.eval_diffusion import evaluate_perplexity as ppl
|
| 321 |
+
length = cfg.llada_ppl_seq_len
|
| 322 |
+
kw = dict(model=model, tokenizer=tokenizer, dataset=dataset, seq_len=length, device=cfg.device,
|
| 323 |
+
mc_num=cfg.mc_num, mc_batch_size=cfg.batch_size,
|
| 324 |
+
resume_path=output / ("perplexity_" + dataset + "_resume.pt"),
|
| 325 |
+
resume_signature=signature, deadline=deadline)
|
| 326 |
+
if family == "dream":
|
| 327 |
+
kw["sampling_eps"] = cfg.sampling_eps
|
| 328 |
+
value = float(ppl(**kw))
|
| 329 |
+
import math
|
| 330 |
+
if not math.isfinite(value):
|
| 331 |
+
raise ValueError("Non-finite perplexity")
|
| 332 |
+
record = {"kind": "perplexity", "complete": True, "metadata": metadata, "value": value,
|
| 333 |
+
"results": {"dataset": dataset, "perplexity": value}}
|
| 334 |
+
except EvaluationContinuation:
|
| 335 |
+
print("Progress saved; resume this unit in the next session:", unit, flush=True)
|
| 336 |
+
return {"complete": False, "completed_units": completed, "pending_unit": unit}
|
| 337 |
+
write_json(path, record)
|
| 338 |
+
completed.append(unit)
|
| 339 |
+
print("Saved:", path, flush=True)
|
| 340 |
+
return {"complete": True, "completed_units": completed, "pending_unit": None}
|
| 341 |
+
|
| 342 |
+
|
| 343 |
def main():
|
| 344 |
parser = argparse.ArgumentParser(description=__doc__)
|
| 345 |
parser.add_argument("--repo")
|
|
|
|
| 351 |
parser.add_argument("--owner", default=DEFAULT_OWNER)
|
| 352 |
parser.add_argument("--run", default=DEFAULT_RUN)
|
| 353 |
parser.add_argument("--tasks", nargs="+")
|
| 354 |
+
parser.add_argument("--units", nargs="+", help="Specific task:name or ppl:dataset units; supports PPL-only sessions")
|
| 355 |
+
parser.add_argument("--time-budget-seconds", type=float, default=0, help="Stop after committing a response/sequence; zero is unlimited")
|
| 356 |
+
parser.add_argument("--request-chunk-size", type=int, default=32, help="Durable likelihood responses per chunk; use 1 on slow GPUs")
|
| 357 |
+
parser.add_argument("--require-finetuned-slice", action="store_true", help="Reject SliceGPT baselines without a sequential LoRA manifest")
|
| 358 |
parser.add_argument("--batch-size", type=int)
|
| 359 |
parser.add_argument("--mc-num", type=int)
|
| 360 |
parser.add_argument("--limit", type=int)
|
| 361 |
parser.add_argument("--dtype", choices=["auto", "bfloat16", "float16", "float32"])
|
| 362 |
+
parser.add_argument("--device", default="cuda")
|
| 363 |
parser.add_argument("--device-map", choices=["auto", "single"], default="auto")
|
| 364 |
parser.add_argument("--gpu-memory-ratio", type=float, default=0.65)
|
| 365 |
parser.add_argument("--cpu-memory-gib", type=float)
|
|
|
|
| 382 |
parser.error("Supply --repo or --checkpoint")
|
| 383 |
import torch
|
| 384 |
from huggingface_hub import HfApi, snapshot_download
|
| 385 |
+
if args.time_budget_seconds < 0 or args.request_chunk_size < 1:
|
| 386 |
+
raise ValueError("Time budget must be nonnegative and chunk size positive")
|
| 387 |
+
deadline = time.monotonic() + args.time_budget_seconds if args.time_budget_seconds else None
|
| 388 |
cfg = DiffusionEvalConfig()
|
| 389 |
cfg.device = args.device
|
| 390 |
for key in ("batch_size", "mc_num", "limit"):
|
|
|
|
| 396 |
cfg.dtype = "bfloat16" if cfg.device.startswith("cuda") and torch.cuda.is_bf16_supported() else "float16" if cfg.device.startswith("cuda") else "float32"
|
| 397 |
if cfg.batch_size <= 0 or cfg.mc_num <= 0 or cfg.mc_num % cfg.batch_size:
|
| 398 |
raise ValueError("batch-size must be positive and divide mc-num")
|
| 399 |
+
if not args.show_config and cfg.device.startswith("cuda") and not torch.cuda.is_available():
|
| 400 |
raise RuntimeError("Enable a GPU runtime or pass --device cpu")
|
| 401 |
+
if not args.show_config and cfg.dtype == "bfloat16" and cfg.device.startswith("cuda") and not torch.cuda.is_bf16_supported():
|
| 402 |
raise RuntimeError("This GPU needs --dtype auto or --dtype float16; the override is recorded in results")
|
| 403 |
if args.show_config:
|
| 404 |
family = args.family or ("dream" if "structured-dream-" in (args.repo or "") else "llada")
|
| 405 |
tasks = args.tasks or (cfg.dream_tasks or cfg.llada_tasks if family == "dream" else cfg.llada_tasks)
|
| 406 |
print(json.dumps({"family": family, "eval_config": asdict(cfg),
|
| 407 |
"adapter_parameters": adapter_parameters(cfg, family),
|
| 408 |
+
"worker_tasks": [u.split(":", 1)[1] for u in evaluation_units(cfg, family, args.tasks, args.units,
|
| 409 |
+
args.worker_index, args.num_workers) if u.startswith("task:")],
|
| 410 |
+
"worker_units": evaluation_units(cfg, family, args.tasks, args.units, args.worker_index, args.num_workers),
|
| 411 |
"perplexity_enabled": not cfg.skip_ppl,
|
| 412 |
"note": "llada_generation_* are separate helper defaults; the benchmark uses llada_steps/llada_gen_length/llada_block_length."}, indent=2))
|
| 413 |
return
|
|
|
|
| 420 |
checkpoint = snapshot_download(args.repo, revision=revision, token=token, cache_dir=args.cache_dir)
|
| 421 |
root = Path(checkpoint)
|
| 422 |
saved = json.loads((root / "checkpoint_manifest.json").read_text()) if (root / "checkpoint_manifest.json").exists() else None
|
| 423 |
+
manifest_job = (saved.get("job", saved.get("provenance", {}).get("job", {})) if saved else {})
|
| 424 |
+
family = args.family or ("dream" if manifest_job.get("model", "").startswith("Dream-org/") else "llada")
|
| 425 |
if (root / "slicegpt_metadata.json").exists():
|
| 426 |
family = json.loads((root / "slicegpt_metadata.json").read_text())["family"]
|
| 427 |
+
if args.require_finetuned_slice and (root / "slicegpt_metadata.json").exists() and not (root / "finetune_manifest.json").exists():
|
| 428 |
+
raise ValueError("This SliceGPT checkpoint has not completed sequential LoRA; choose a fine-tuned repo or remove --require-finetuned-slice to explicitly evaluate the pruned baseline")
|
| 429 |
seed_all(cfg.seed)
|
| 430 |
model, tokenizer = load_checkpoint(checkpoint, cfg, args.device_map, args.gpu_memory_ratio,
|
| 431 |
args.cpu_memory_gib, str(Path(args.offload_dir) / f"worker-{args.worker_index}"))
|
|
|
|
| 433 |
"family": family, "torch_version": torch.__version__,
|
| 434 |
"device_map": getattr(model, "hf_device_map", {"": cfg.device})}
|
| 435 |
label = (args.repo or root.name).split("/")[-1]
|
| 436 |
+
profile = hashlib.sha256(json.dumps(asdict(cfg), sort_keys=True).encode()).hexdigest()[:12]
|
| 437 |
+
output = Path(args.output) / label / revision[:12] / profile
|
| 438 |
+
write_json(output / "effective_config.json", {"metadata": metadata, "shared_source": "Pruning-LLMs/diffusion_eval_and_vis/config.py"})
|
| 439 |
if args.smoke:
|
| 440 |
inputs = tokenizer("The quick brown fox.", return_tensors="pt").input_ids.to(cfg.device)
|
| 441 |
with torch.no_grad():
|
|
|
|
| 445 |
write_json(output / "smoke.json", {"complete": True, "metadata": metadata, "shape": list(logits.shape)})
|
| 446 |
print(json.dumps({"smoke_passed": True, "output": str(output), "metadata": metadata}, default=str))
|
| 447 |
return
|
| 448 |
+
units = evaluation_units(cfg, family, args.tasks, args.units, args.worker_index, args.num_workers)
|
| 449 |
+
status = run_units(model, tokenizer, cfg, family, checkpoint, metadata, output, units,
|
| 450 |
+
deadline=deadline, request_chunk_size=args.request_chunk_size)
|
| 451 |
+
write_json(output / "session_status.json", status)
|
| 452 |
+
print(json.dumps({"output": str(output), **status}), flush=True)
|
| 453 |
+
del model, tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
gc.collect()
|
| 455 |
if torch.cuda.is_available():
|
| 456 |
torch.cuda.empty_cache()
|