File size: 10,349 Bytes
cb8c6af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"""Full-horizon, discovery-only feasibility pilot for Experiment 001D."""

from __future__ import annotations

import gzip
import hashlib
import json
import time
from pathlib import Path

import modal


CONFIG_PATH = "results/experiment_001d/stage1_fast_v2/controller_long_pilot_config.json"
OUTPUT_DIR = Path("results/experiment_001d/stage1_fast_v2")
BASE_REVISION = "2fc06364715b967f1860aea9cf38778875588b17"
EDITED_REVISION = "d1671a178705bcab7644806d23c535517f35723b"
REMOTE_BASE = f"/cache/modelclinic/base-{BASE_REVISION}"
REMOTE_EDITED = f"/cache/modelclinic/edited-{EDITED_REVISION}"
VOLUME = modal.Volume.from_name("research-cache", create_if_missing=False)

image = (
    modal.Image.debian_slim(python_version="3.11")
    .pip_install("vllm==0.33.0", "transformers==5.20.2", "safetensors==0.8.0")
    .env({"VLLM_USE_FLASHINFER_SAMPLER": "0", "VLLM_ALLOW_INSECURE_SERIALIZATION": "1"})
    .add_local_file("src/experiment_001d_runtime.py", "/root/project/experiment_001d_runtime.py")
    .add_local_file("src/experiment_001d_behavioral.py", "/root/project/experiment_001d_analysis.py")
    .add_local_file("results/experiment_001b/calibration_long/calibration.json", "/root/project/calibration.json")
    .add_local_file(CONFIG_PATH, "/root/project/long_pilot_config.json")
)

app = modal.App("modelclinic-experiment-001d-long-controller-pilot")


def _json_bytes(value: object) -> bytes:
    return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8")


@app.function(
    image=image,
    gpu="A10",
    volumes={"/cache": VOLUME},
    cpu=2,
    memory=8192,
    timeout=1800,
    retries=0,
    scaledown_window=2,
    max_containers=1,
)
def run_long_pilot():
    import os
    import sys

    sys.path.insert(0, "/root/project")
    import torch
    import vllm
    from transformers import AutoTokenizer
    from vllm import LLM, SamplingParams

    from experiment_001d_analysis import extract_final_number, repetition_metrics, score_completion, is_repetitive_prefix
    from experiment_001d_runtime import (
        expected_active_positions,
        install_controller_hooks,
        read_controller_stats,
        remove_controller_hooks,
    )

    if os.environ.get("VLLM_ALLOW_INSECURE_SERIALIZATION") != "1":
        raise RuntimeError("trusted apply_model callback serialization is not enabled")
    VOLUME.reload()
    for required in (REMOTE_BASE, REMOTE_EDITED):
        if not Path(required).is_dir():
            raise RuntimeError(f"cached checkpoint is missing: {required}")
    config = json.loads(Path("/root/project/long_pilot_config.json").read_text(encoding="utf-8"))
    calibration = json.loads(Path("/root/project/calibration.json").read_text(encoding="utf-8"))
    prefix_ids = [int(x) for x in config["prefix_token_ids"]]
    prefix_sha = hashlib.sha256(_json_bytes(prefix_ids)).hexdigest()
    if prefix_sha != config["prefix_sha256"]:
        raise RuntimeError(f"prefix hash mismatch: computed={prefix_sha} config={config['prefix_sha256']}")
    torch.set_grad_enabled(False)
    torch.set_num_threads(2)
    tokenizer = AutoTokenizer.from_pretrained(REMOTE_BASE, local_files_only=True)
    llm = LLM(
        model=REMOTE_BASE,
        dtype="bfloat16",
        gpu_memory_utilization=0.8,
        max_model_len=int(config["model_max_len"]),
        max_num_seqs=1,
        max_num_batched_tokens=int(config["model_max_len"]),
        enable_prefix_caching=False,
        enforce_eager=True,
        seed=20261104,
        trust_remote_code=False,
    )
    constants = calibration["selected"]["published_constant"]["coefficients"]
    layer_data = {}
    for layer in (15, 19):
        key = str(layer)
        layer_data[key] = {
            "direction": calibration["layers"][key]["direction"],
            "gate_vector": calibration["layers"][key]["rank1_gate_vector"],
            "constant": float(constants[key]),
            "donor_coefficients": config["donor_coefficients"][key],
            "donor_scale": float(config["donor_scale"][key]),
            "donor_offset": float(config["donor_offset"][key]),
        }
    sampling = SamplingParams(
        n=1,
        temperature=0.6,
        top_p=0.95,
        top_k=20,
        presence_penalty=1.5,
        max_tokens=int(config["horizon"]),
        seed=int(config["sampling"]["seed"]),
    )
    prefix_text = tokenizer.decode(config["prefix_generated_token_ids"], skip_special_tokens=False)
    started = time.monotonic()
    results = []
    for condition in config["conditions"]:
        hook_config = {
            "mode": condition,
            "prefix_length": len(prefix_ids),
            "layers": layer_data,
            "edited_checkpoint_path": f"{REMOTE_EDITED}/model.safetensors-00001-of-00001.safetensors",
        }
        installed = llm.apply_model(lambda worker, _cfg=hook_config: install_controller_hooks(worker, _cfg))
        if not installed:
            raise RuntimeError(f"controller hooks were not installed for {condition}")
        output = llm.generate(
            [{"prompt_token_ids": prefix_ids}],
            sampling,
            use_tqdm=False,
        )[0].outputs[0]
        stats = llm.apply_model(read_controller_stats)
        if not stats or len(stats) != 1:
            raise RuntimeError(f"expected one worker stats result for {condition}")
        stats = stats[0]
        removed = llm.apply_model(remove_controller_hooks)
        generated_ids = [int(x) for x in output.token_ids]
        expected_positions = expected_active_positions(generated_ids, tokenizer.eos_token_id)
        continuation_text = tokenizer.decode(generated_ids, skip_special_tokens=False)
        full_assistant_text = prefix_text + continuation_text
        finish_reason = str(output.finish_reason or "unknown")
        natural_stop = finish_reason == "stop"
        combined_ids = [int(x) for x in config["prefix_generated_token_ids"]] + generated_ids
        repetition_path = []
        for end in range(int(config["prefix_end_generated_tokens"]) + 64, len(combined_ids) + 1, 64):
            partial_text = tokenizer.decode(combined_ids[:end], skip_special_tokens=False)
            metrics = repetition_metrics(combined_ids[:end], partial_text)
            repetition_path.append({"end_token": end, **metrics, "repetitive": is_repetitive_prefix(metrics)})
        results.append(
            {
                "condition": condition,
                "mode": condition,
                "prefix_token_ids": prefix_ids,
                "prefix_sha256": prefix_sha,
                "target_source_row": int(config["target_source_row"]),
                "donor_source_row": int(config["donor_source_row"]),
                "donor_start_position": int(config["donor_start_position"]),
                "donor_cyclic_rotation": int(config["donor_cyclic_rotation"]),
                "donor_scale": config["donor_scale"],
                "generated_token_ids": generated_ids,
                "continuation_text": continuation_text,
                "full_assistant_text": full_assistant_text,
                "prefix_answer": extract_final_number(prefix_text),
                "continuation_score": score_completion(continuation_text, str(config["gold_answer"]), finish_reason, natural_stop),
                "score": score_completion(full_assistant_text, str(config["gold_answer"]), finish_reason, natural_stop),
                "finish_reason": finish_reason,
                "stop_reason": output.stop_reason,
                "natural_stop": natural_stop,
                "eos_token_id": tokenizer.eos_token_id,
                "eos_in_output": tokenizer.eos_token_id is not None and int(tokenizer.eos_token_id) in generated_ids,
                "expected_active_positions": expected_positions,
                "layer_stats": stats,
                "hook_position_counts_valid": all(
                    int(stats[str(layer)]["active_positions"]) == expected_positions
                    for layer in (15, 19)
                ),
                "hooks_removed": removed[0] if removed else [],
                "repetition_path": repetition_path,
            }
        )
        print(
            f"long-pilot condition={condition} tokens={len(generated_ids)} "
            f"finish={finish_reason} counters_valid={results[-1]['hook_position_counts_valid']}",
            flush=True,
        )
    return {
        "run_id": config["run_id"],
        "stage": config["stage"],
        "source_manifest_sha256": config["source_manifest_sha256"],
        "config_sha256": hashlib.sha256(Path("/root/project/long_pilot_config.json").read_bytes()).hexdigest(),
        "elapsed_seconds": time.monotonic() - started,
        "gpu": torch.cuda.get_device_name(),
        "vllm_version": vllm.__version__,
        "torch_version": torch.__version__,
        "prefix_sha256": prefix_sha,
        "all_prefixes_identical": len({x["prefix_sha256"] for x in results}) == 1,
        "all_hook_position_counts_valid": all(x["hook_position_counts_valid"] for x in results),
        "donor_scale_estimation": config["donor_scale_estimation"],
        "sampling": config["sampling"],
        "results": results,
    }


@app.local_entrypoint()
def main():
    output = OUTPUT_DIR / "controller_long_pilot_v1.json.gz"
    summary_path = OUTPUT_DIR / "controller_long_pilot_summary.json"
    if output.exists() or summary_path.exists():
        raise RuntimeError("refusing to overwrite prior full-horizon pilot artifacts")
    result = run_long_pilot.remote()
    with gzip.open(output, "wt", encoding="utf-8") as handle:
        json.dump(result, handle, ensure_ascii=False, separators=(",", ":"))
    summary = {
        key: result[key]
        for key in (
            "run_id",
            "stage",
            "source_manifest_sha256",
            "config_sha256",
            "elapsed_seconds",
            "gpu",
            "prefix_sha256",
            "all_prefixes_identical",
            "all_hook_position_counts_valid",
        )
    }
    summary["conditions"] = [
        {"condition": x["condition"], "tokens": len(x["generated_token_ids"]), "finish_reason": x["finish_reason"], "score": x["score"]}
        for x in result["results"]
    ]
    summary_path.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(summary, indent=2))