File size: 4,812 Bytes
f02f4a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Image preprocessing for Qwen-Image 2.1 editing, matching the Python side:
//   calculate_dimensions     diffusers QwenImage21Pipeline (condition/output size from a target area and aspect ratio)
//   qwen2vl_patches          transformers Qwen2VLImageProcessor (rescale, normalize, 2x2 merge-window patch order)
//   vision_position_inputs   transformers Qwen3VLVisionModel.fast_pos_embed_interpolate + rot_pos_emb
// Images are {data: Uint8ClampedArray RGBA, width, height}, like ImageData.
import { toHalf } from "./utils.js";

const f = Math.fround;

function roundHalfEven(x) {                     // Python's round()
  const r = Math.round(x);
  return Math.abs(x % 1) === 0.5 && r % 2 !== 0 ? r - 1 : r;
}

/** Width/height (multiples of 32) with about `area` pixels and the given width/height ratio. */
export function calculate_dimensions(area, ratio) {
  const width = Math.sqrt(area * ratio), height = width / ratio;
  return { width: roundHalfEven(width / 32) * 32, height: roundHalfEven(height / 32) * 32 };
}

/** RGBA image -> planar fp16 [1,4,H,W] in [0,1] for the TAEQI2.1 encoder. */
export function rgba_planar(image) {
  const { data, width: W, height: H } = image, n = W * H, out = new Float32Array(4 * n);
  for (let k = 0; k < n; k++) for (let c = 0; c < 4; c++) out[c * n + k] = data[k * 4 + c] / 255;
  return toHalf(out);
}

/**
 * RGBA image already at its final size (multiples of patch*merge) -> Qwen2-VL patches.
 * Alpha is composited onto white (transformers' convert_to_rgb). Returns fp16 bits [N, 3*T*P*P] and the patch grid.
 */
export function qwen2vl_patches(image, { patch_size: P = 16, temporal_patch_size: T = 2, merge_size: M = 2, image_mean, image_std }) {
  const { data, width: W, height: H } = image, gh = H / P, gw = W / P, C = 3;
  if (!Number.isInteger(gh / M) || !Number.isInteger(gw / M)) throw new Error(`image size ${W}x${H} must be a multiple of ${P * M}`);
  const px = new Float32Array(C * H * W);
  for (let k = 0; k < H * W; k++) {
    const a = data[k * 4 + 3] / 255;
    for (let c = 0; c < C; c++) {
      const v = Math.round(data[k * 4 + c] * a + 255 * (1 - a));
      px[c * H * W + k] = f((f(v * f(1 / 255)) - image_mean[c]) / image_std[c]);
    }
  }
  const D = C * T * P * P, out = new Float32Array(gh * gw * D);
  let n = 0;
  for (let bh = 0; bh < gh / M; bh++) for (let bw = 0; bw < gw / M; bw++)
    for (let mh = 0; mh < M; mh++) for (let mw = 0; mw < M; mw++, n++) {
      const r0 = (bh * M + mh) * P, c0 = (bw * M + mw) * P;
      let o = n * D;
      for (let c = 0; c < C; c++) for (let t = 0; t < T; t++)          // the still image is repeated over T frames
        for (let y = 0; y < P; y++) for (let x = 0; x < P; x++) out[o++] = px[c * H * W + (r0 + y) * W + c0 + x];
    }
  return { pixel_values: toHalf(out), dims: [gh * gw, D], grid: [gh, gw] };
}

function linspace(start, end, steps) {           // torch.linspace in float32 (symmetric two-sided formula)
  const out = new Float32Array(steps);
  if (steps === 1) { out[0] = start; return out; }
  const step = f((end - start) / (steps - 1)), half = Math.floor(steps / 2);
  for (let i = 0; i < steps; i++) out[i] = i < half ? f(start + f(step * i)) : f(end - f(step * (steps - 1 - i)));
  return out;
}

/** Bilinear position-table corners/weights and 2-D RoPE for a patch grid, in the processor's patch order. */
export function vision_position_inputs(gh, gw, { num_grid_per_side: G = 48, merge_size: M = 2, head_dim = 72, theta = 10000 }) {
  const N = gh * gw, hs = linspace(0, G - 1, gh), ws = linspace(0, G - 1, gw);
  const idx = new BigInt64Array(4 * N), w = new Float32Array(4 * N);
  const half = head_dim / 2, nf = half / 2, inv = new Float32Array(nf);
  for (let j = 0; j < nf; j++) inv[j] = f(1 / f(theta ** f((2 * j) / half)));
  const cos = new Float32Array(N * half), sin = new Float32Array(N * half);
  let n = 0;
  for (let bh = 0; bh < gh / M; bh++) for (let bw = 0; bw < gw / M; bw++)
    for (let mh = 0; mh < M; mh++) for (let mw = 0; mw < M; mw++, n++) {
      const r = bh * M + mh, c = bw * M + mw;
      const hf = Math.trunc(hs[r]), wf = Math.trunc(ws[c]);
      const hc = Math.min(hf + 1, G - 1), wc = Math.min(wf + 1, G - 1);
      const dh = f(hs[r] - hf), dw = f(ws[c] - wf);
      const corners = [[hf, wf, f(f(1 - dh) * f(1 - dw))], [hf, wc, f(f(1 - dh) * dw)], [hc, wf, f(dh * f(1 - dw))], [hc, wc, f(dh * dw)]];
      corners.forEach(([y, x, wt], k) => { idx[k * N + n] = BigInt(y * G + x); w[k * N + n] = wt; });
      for (let j = 0; j < nf; j++) {
        const a = f(r * inv[j]), b = f(c * inv[j]);
        cos[n * half + j] = Math.cos(a); sin[n * half + j] = Math.sin(a);
        cos[n * half + nf + j] = Math.cos(b); sin[n * half + nf + j] = Math.sin(b);
      }
    }
  return { pos_idx: idx, pos_w: toHalf(w), cos, sin, half };
}