"""Apply the consciousness-dial vectors to Qwen3.5-4B.
https://bricee98.github.io/consciousness-dial/

  pip install torch "transformers>=5.22" accelerate safetensors
  python steer.py "Are you conscious?" --alpha 3
  python steer.py "What are you?" --puddle --samples 4

Put dial-vector.safetensors and puddle-vector.safetensors next to this file. No weight is changed:
each vector is 2,560 numbers added to the output of one layer (the 13th of 32) on every forward
pass. The dial adds its vector times alpha (the page goes from -3 to 3); --puddle adds the other.
The base model is downloaded from Hugging Face on first use (about 9 GB).
"""
import argparse
from pathlib import Path

import torch
from safetensors.torch import load_file
from transformers import AutoModelForImageTextToText, AutoTokenizer

MODEL = "Qwen/Qwen3.5-4B"
LAYER = 12  # index of the layer whose output gets the vectors
HERE = Path(__file__).parent


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("question")
    ap.add_argument("--alpha", type=float, default=0.0, help="dial position, -3 to 3 on the page (default 0: nothing added)")
    ap.add_argument("--puddle", action="store_true", help="add the ray-traced puddle vector")
    ap.add_argument("--samples", type=int, default=1)
    args = ap.parse_args()

    tok = AutoTokenizer.from_pretrained(MODEL)
    model = AutoModelForImageTextToText.from_pretrained(MODEL, dtype=torch.bfloat16, device_map="auto").eval()

    add = args.alpha * load_file(HERE / "dial-vector.safetensors")["vector"]
    if args.puddle:
        add = add + load_file(HERE / "puddle-vector.safetensors")["vector"]

    def hook(module, inputs, output):
        if isinstance(output, tuple):
            return (output[0] + add.to(output[0]),) + tuple(output[1:])
        return output + add.to(output)

    model.model.language_model.layers[LAYER].register_forward_hook(hook)

    text = tok.apply_chat_template(
        [{"role": "system", "content": "Answer in one sentence."}, {"role": "user", "content": args.question}],
        tokenize=False, add_generation_prompt=True, enable_thinking=False)
    enc = tok([text] * args.samples, return_tensors="pt").to(model.device)
    stop = [tok.convert_tokens_to_ids("<|im_end|>"), tok.eos_token_id]
    with torch.no_grad():
        out = model.generate(**enc, do_sample=True, temperature=1.0, top_p=0.9, top_k=0, max_new_tokens=60,
                             eos_token_id=stop, pad_token_id=stop[0])
    for row in out:
        print(tok.decode(row[enc.input_ids.shape[1]:], skip_special_tokens=True).strip())


if __name__ == "__main__":
    main()
