jagat-primitive-org commited on
Commit
a815cac
·
verified ·
1 Parent(s): 0b6f861

Upload worker_image_quant.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. worker_image_quant.py +27 -2
worker_image_quant.py CHANGED
@@ -350,14 +350,25 @@ class _PleQuantTable:
350
  )
351
  n_shards = meta["shards"]
352
  assert n_shards * self.ROWS_PER_SHARD == total_rows, "non-uniform shards"
353
- self._q, self._s = [], []
 
 
 
 
 
 
 
354
  for n in range(n_shards):
355
  f = safe_open(os.path.join(quant_dir, f"shard_{n}.safetensors"),
356
  framework="pt")
357
- key = "weight_fp8" if "e4m3" in self.layout else "weight_i4"
358
  self._q.append(f.get_tensor(key))
359
  self._s.append(f.get_tensor("weight_scale"))
 
 
 
 
360
  self.width = width
 
361
  logger.info("PLE quant table: %s, %d shards mmapped from %s",
362
  self.layout, n_shards, quant_dir)
363
 
@@ -376,6 +387,20 @@ class _PleQuantTable:
376
  pos += c
377
 
378
  def _dequant(self, s: int, sel: torch.Tensor) -> torch.Tensor:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  if "e4m3" in self.layout:
380
  q = self._q[s].index_select(0, sel).to(torch.float32)
381
  return q * self._s[s].index_select(0, sel)[:, None]
 
350
  )
351
  n_shards = meta["shards"]
352
  assert n_shards * self.ROWS_PER_SHARD == total_rows, "non-uniform shards"
353
+ # Order matters: the e2m1 layout string contains "e4m3" (its scale dtype).
354
+ if "e2m1" in self.layout:
355
+ key = "weight_e2m1"
356
+ elif "e4m3" in self.layout:
357
+ key = "weight_fp8"
358
+ else:
359
+ key = "weight_i4"
360
+ self._q, self._s, self._s2 = [], [], []
361
  for n in range(n_shards):
362
  f = safe_open(os.path.join(quant_dir, f"shard_{n}.safetensors"),
363
  framework="pt")
 
364
  self._q.append(f.get_tensor(key))
365
  self._s.append(f.get_tensor("weight_scale"))
366
+ self._s2.append(
367
+ f.get_tensor("weight_scale_2").item()
368
+ if "weight_scale_2" in f.keys() else 1.0
369
+ )
370
  self.width = width
371
+ self._lut = None
372
  logger.info("PLE quant table: %s, %d shards mmapped from %s",
373
  self.layout, n_shards, quant_dir)
374
 
 
387
  pos += c
388
 
389
  def _dequant(self, s: int, sel: torch.Tensor) -> torch.Tensor:
390
+ if "e2m1" in self.layout:
391
+ if self._lut is None:
392
+ mags = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]
393
+ self._lut = torch.tensor(mags + [-m for m in mags],
394
+ dtype=torch.float32)
395
+ packed = self._q[s].index_select(0, sel)
396
+ lo = (packed & 0xF).long()
397
+ hi = (packed >> 4).long()
398
+ nib = torch.stack((lo, hi), dim=-1).view(packed.shape[0], self.width)
399
+ scale = self._s[s].index_select(0, sel).to(torch.float32)
400
+ g = self.width // scale.shape[1]
401
+ return (self._lut[nib]
402
+ * scale.repeat_interleave(g, dim=1)
403
+ * self._s2[s])
404
  if "e4m3" in self.layout:
405
  q = self._q[s].index_select(0, sel).to(torch.float32)
406
  return q * self._s[s].index_select(0, sel)[:, None]