File size: 5,814 Bytes
4d925ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Apply the weight-space-programmed depth patch to DeepSeek's Janus-Pro-1B, and ask it a depth question.

    pip install torch transformers huggingface_hub pillow numpy
    python apply_patch.py                                   # the three example scenes, before and after the patch
    python apply_patch.py --image my.png --question "Is the tree in the foreground or in the background?"

The patch changes 12,288 numbers in layer 23's MLP (two neurons: one gate row, one up row and one down column each).
Every edited tensor is checked against the SHA-256 recorded in patch/manifest.json, before and after the edit, so a
patched model is provably the official checkpoint plus exactly this delta. `revert` restores the original bit for bit.

The base weights are not in this repository; they are downloaded from deepseek-community/Janus-Pro-1B at the pinned
revision the patch was computed against. The model must run in float32: the patch was fitted against float32 weights
and is smaller than bfloat16 rounding.
"""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
from typing import Any

import numpy as np
import torch
from PIL import Image
from transformers import JanusForConditionalGeneration, JanusProcessor

BASE_MODEL = "deepseek-community/Janus-Pro-1B"
BASE_REVISION = "1655280bb75959cc1cb85529a2a8b26e7016072e"
HERE = Path(__file__).resolve().parent


def sha256(t: torch.Tensor) -> str:
    """SHA-256 of the tensor's contiguous little-endian CPU bytes (the manifest's hash convention)."""
    return hashlib.sha256(t.detach().to("cpu").contiguous().numpy().tobytes(order="C")).hexdigest()


def load_base(device: str = "cpu") -> tuple[JanusForConditionalGeneration, JanusProcessor]:
    model = JanusForConditionalGeneration.from_pretrained(BASE_MODEL, revision=BASE_REVISION, dtype=torch.float32, device_map={"": device}, attn_implementation="eager")
    processor = JanusProcessor.from_pretrained(BASE_MODEL, revision=BASE_REVISION)
    return model.eval(), processor


def apply(model: JanusForConditionalGeneration, patch_dir: Path = HERE / "patch") -> dict[str, torch.Tensor]:
    """Add every delta in the patch set in place. Returns the original tensors, for `revert`."""
    manifest = json.loads((patch_dir / "manifest.json").read_text())
    params = dict(model.named_parameters())
    originals: dict[str, torch.Tensor] = {}
    for d in manifest["deltas"]:
        p = params[d["tensor_name"]]
        if list(p.shape) != d["shape"] or str(p.dtype).removeprefix("torch.") != d["dtype"]:
            raise ValueError(f"{d['tensor_name']}: expected {d['dtype']} {d['shape']}, found {p.dtype} {list(p.shape)}; load the model in float32")
        if sha256(p) != d["base_hash"]:
            raise ValueError(f"{d['tensor_name']} is not the weight this patch was computed against (wrong revision or already patched)")
        indices = torch.from_numpy(np.load(patch_dir / d["files"]["indices"])).to(p.device)
        values = torch.from_numpy(np.load(patch_dir / d["files"]["values"])).to(device=p.device, dtype=p.dtype)
        originals[d["tensor_name"]] = p.detach().clone()
        with torch.no_grad():
            p.view(-1).index_add_(0, indices, values)
        if sha256(p) != d["edited_hash"]:
            raise ValueError(f"{d['tensor_name']}: the patched tensor does not match the recorded edited hash")
    return originals


def revert(model: JanusForConditionalGeneration, originals: dict[str, torch.Tensor]) -> None:
    params = dict(model.named_parameters())
    with torch.no_grad():
        for name, t in originals.items():
            params[name].copy_(t)


@torch.no_grad()
def ask(model: JanusForConditionalGeneration, processor: JanusProcessor, image: Image.Image, question: str) -> str:
    """Greedy answer, the same chat template and decoding the evaluation used."""
    messages = [{"role": "user", "content": [{"type": "image", "image": image}, {"type": "text", "text": question}]}]
    raw: Any = processor.apply_chat_template(messages, add_generation_prompt=True, generation_mode="text", tokenize=True, return_dict=True, return_tensors="pt")
    inputs = raw.to(model.device)
    out = model.generate(**inputs, generation_mode="text", do_sample=False, max_new_tokens=24, use_cache=True)
    return processor.tokenizer.decode(out[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True).strip()


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--image")
    ap.add_argument("--question")
    ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
    a = ap.parse_args()
    if a.image:
        cases = [{"image": a.image, "question": a.question or "Is the object in the foreground or in the background?"}]
    else:
        cases = json.loads((HERE / "examples/answers.json").read_text())
    model, processor = load_base(a.device)
    images = [Image.open(Path(c["image"]) if a.image else HERE / c["image"]).convert("RGB") for c in cases]
    before = [ask(model, processor, im, c["question"]) for im, c in zip(images, cases)]
    originals = apply(model)
    print("patch applied; all base and edited hashes match the manifest")
    after = [ask(model, processor, im, c["question"]) for im, c in zip(images, cases)]
    for c, b, f in zip(cases, before, after):
        print(f"\n{c['image']}  {c['question']}" + (f"  (truth: {c['truth']})" if "truth" in c else ""))
        print(f"  unchanged model:  {b}")
        print(f"  programmed model: {f}")
    revert(model, originals)
    print("\nreverted; base hashes:", all(sha256(dict(model.named_parameters())[n]) == t for n, t in ((d["tensor_name"], d["base_hash"]) for d in json.loads((HERE / "patch/manifest.json").read_text())["deltas"])))


if __name__ == "__main__":
    main()