File size: 7,619 Bytes
362b32d | 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 | """SHADOW picture codes for video: frames at 1 per second (at most 64), repeated frames dropped, the int8 eye run in fp16, 512-bit codes
sign(W^T (v - pic_mu)), written as shards (codes, image index, captions, text token counts).
Needs eye_int8.safetensors and shadow_table_v1.npz from the SHADOW release."""
import io, json, math, pathlib, tarfile, zipfile
import numpy as np, torch
from PIL import Image
from safetensors.torch import load_file
from transformers import AutoTokenizer
BUDGETS = (70, 140, 280, 560, 1120)
VIDEO_EXT = (".mp4", ".mov", ".mkv", ".webm", ".avi")
def budget(w, h, cap=140):
native = max(w * h / 2304, 1.0)
return min((b for b in BUDGETS if b <= cap), key=lambda b: abs(math.log(b / native)))
def fwht256(x):
s = x.shape
x = x.reshape(-1, 256).clone()
h = 1
while h < 256:
x = x.view(-1, 256 // (2 * h), 2, h)
a, c = x[:, :, 0, :].clone(), x[:, :, 1, :].clone()
x[:, :, 0, :], x[:, :, 1, :] = a + c, a - c
x = x.view(-1, 256)
h *= 2
return x.view(s)
def int8_weight(qweight, qscale):
n, k = qweight.shape
g = torch.Generator().manual_seed(k)
sign = (torch.randint(0, 2, (k,), generator=g) * 2 - 1).float()
w = (qweight.float().view(n, k // 256, 256) * qscale.float()[:, :, None]).reshape(n, k)
return fwht256(w) / 16.0 * sign[None]
class Eye:
def __init__(self, eye_path, table_path, dev="cuda"):
from sentence_transformers import SentenceTransformer
st = SentenceTransformer("google/embeddinggemma-2", device=dev, model_kwargs={"torch_dtype": torch.float32})
self.hf, self.ip, self.dev = st[0].model, st[0].processor.image_processor, dev
f = load_file(eye_path)
self.hf.load_state_dict({k: v for k, v in f.items() if not k.endswith((".qweight", ".qscale"))}, strict=False)
mods = dict(self.hf.named_modules())
with torch.no_grad():
for k in f:
if k.endswith(".qweight"):
lin = mods[k[:-8]]
lin.weight.copy_(int8_weight(f[k], f[k[:-8] + ".qscale"]).to(lin.weight.device))
self.hf.eval()
z = np.load(table_path)
self.W = torch.from_numpy(z["W"]).float().to(dev)
self.mu = torch.from_numpy(z["pic_mu"]).float().to(dev)
@torch.no_grad()
def codes(self, images, budgets):
out, groups = [None] * len(images), {}
for i, b in enumerate(budgets):
groups.setdefault(b, []).append(i)
for b, idx in groups.items():
x = self.ip([images[i] for i in idx], max_soft_tokens=b, return_tensors="pt")
with torch.autocast("cuda", dtype=torch.float16, enabled=self.dev != "cpu"):
r = self.hf.get_image_features(pixel_values=x["pixel_values"].to(self.dev),
image_position_ids=x["image_position_ids"].to(self.dev)).pooler_output
for i, v in zip(idx, r):
v = v.float()
v = v / v.norm(dim=1, keepdim=True)
out[i] = np.packbits(((v - self.mu) @ self.W >= 0).cpu().numpy(), axis=1)
return out
def drop_repeats(fr, times, same=4.0):
keep, kt, last = [], [], None
for f, t in zip(fr, times):
g = np.asarray(f.convert("L").resize((32, 32), Image.BILINEAR), np.float32)
if last is not None and np.abs(g - last).mean() < same:
continue
keep.append(f)
kt.append(t)
last = g
return keep, kt
def frames(video, cap=64):
import av
c = av.open(io.BytesIO(video))
s = c.streams.video[0]
s.thread_type = "AUTO"
dur = float(s.duration * s.time_base) if s.duration else float((c.duration or 0) / 1e6)
if dur > 2 * cap:
s.codec_context.skip_frame = "NONKEY"
n = min(cap, max(1, int(dur)))
want = [dur * (i + 0.5) / n for i in range(n)]
out, times, k = [], [], 0
for f in c.decode(s):
t = float(f.pts * s.time_base) if f.pts is not None else 0.0
if k < n and t >= want[k]:
im = f.to_image().convert("RGB")
while k < n and t >= want[k]:
out.append(im)
times.append(round(t, 2))
k += 1
if k >= n:
break
c.close()
out, times = drop_repeats(out, times)
return out, times, round(dur, 2)
def videos_in(path):
if zipfile.is_zipfile(path):
with zipfile.ZipFile(path) as z:
for n in z.namelist():
if n.lower().endswith(VIDEO_EXT):
yield n, z.read(n)
else:
with tarfile.open(path, "r:*") as t:
for m in t:
if m.isfile() and m.name.lower().endswith(VIDEO_EXT):
yield m.name, t.extractfile(m).read()
def stem(p):
return pathlib.Path(p).name.rsplit(".", 1)[0]
def strings(x):
if isinstance(x, str):
return [x]
if isinstance(x, dict):
return [t for v in x.values() for t in strings(v)]
if isinstance(x, (list, tuple)):
return [t for v in x for t in strings(v)]
return []
class Shards:
def __init__(self, out, name, shard_tokens=4_000_000):
self.dir = pathlib.Path(out) / name
self.dir.mkdir(parents=True, exist_ok=True)
self.name, self.shard_tokens, self.k = name, shard_tokens, 0
self.tok = AutoTokenizer.from_pretrained("google/embeddinggemma-2")
self._reset()
def _reset(self):
self.codes, self.img, self.lines, self.text, self.off = [], [], [], [], 0
def add(self, sid, codes, budgets, sizes, texts, times, src):
idx = []
for c, b, (w, h) in zip(codes, budgets, sizes):
self.codes.append(c)
self.img.append((self.off, len(c), b, w, h))
idx.append(len(self.img) - 1)
self.off += len(c)
self.text += [t for t in strings(texts) if t]
self.lines.append(json.dumps({"id": sid, "src": src, "images": idx, "kind": "frame", "times": times, "texts": texts}, ensure_ascii=False, default=str))
if self.off >= self.shard_tokens:
self.write()
def write(self):
if not self.lines:
return
stem_ = self.dir / f"{self.name}_{self.k:05d}"
np.savez_compressed(f"{stem_}.npz", codes=np.concatenate(self.codes), img=np.array(self.img, np.int64))
counts = np.zeros(262144, np.int64)
for ids in self.tok(self.text, add_special_tokens=False)["input_ids"] if self.text else []:
counts += np.bincount(ids, minlength=262144)[:262144]
np.savez_compressed(f"{stem_}.counts.npz", counts=counts.astype(np.uint32))
pathlib.Path(f"{stem_}.jsonl").write_text("\n".join(self.lines) + "\n", encoding="utf-8")
print(f"{stem_.name}: {len(self.lines)} videos, {self.off:,} picture tokens", flush=True)
self._reset()
self.k += 1
def encode_archive(eye, shards, path, ann, key, name, src):
"""every video in an archive that has annotations: frames, codes, one line each"""
for n, b in videos_in(path):
recs = ann.get(key(n))
if not recs:
continue
try:
fr, times, dur = frames(b)
except Exception:
continue
bud = [budget(*im.size) for im in fr]
shards.add(f"{name}/{n}", eye.codes(fr, bud), bud, [im.size for im in fr], recs, times, dict(src, member=n, duration=dur))
|