MCPcopy Create free account
hub / github.com/FlashSampling/FlashSampling / JLSampler

Class JLSampler

src/fused_mm_sampling/core.py:664–721  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

662 def sample(self, **kwargs) -> torch.Tensor:
663 raise NotImplementedError()
664
665
666@dataclass
667class SimpleSampler(Sampler):
668 fn: Callable[..., torch.Tensor]
669
670 def prepare(self) -> "SimpleSampler":
671 return self
672
673 def sample(self, **kwargs) -> torch.Tensor:
674 return self.fn(**kwargs)
675
676
677@dataclass
678class JLSampler(Sampler):
679 weights: torch.Tensor # [V, D]
680 k: int
681 prepared: bool = False
682
683 @classmethod
684 def from_weights(
685 cls,
686 weights: torch.Tensor, # [V, D]
687 epsilon: float = 0.2,
688 ) -> "JLSampler":
689 k = optimal_k(n=weights.shape[0], epsilon=epsilon)
690 print(f"JLSampler optimal k={k}")
691 return cls(weights, k=k)
692
693 def prepare(self) -> "JLSampler":
694 D = self.weights.shape[1] # noqa: N806
695 self.rand_mat = torch.randn(
696 (D, self.k),
697 dtype=self.weights.dtype,
698 device=self.weights.device,
699 ) / math.sqrt(self.k)
700 self.w_p = self.weights @ self.rand_mat # [V, k]
701 self.w_p = self.w_p.contiguous()
702 self.prepared = True
703 self.weights = None # not needed anymore
704 return self
705
706 @torch.compile(fullgraph=True)
707 def sample(
708 self,
709 hidden_states: torch.Tensor, # [n_hidden_states, D]
710 temperature: torch.Tensor, # scalar (0-d)
711 num_samples: int,
712 seed: int | None = None, # ignored
713 weights: torch.Tensor = None, # ignored
714 ):
715 """
716 Sampling using low-dimensional random projections (Johnson-Lindenstrauss lemma).
717 """
718 if not self.prepared:
719 raise ValueError("Sampler not prepared. Call .prepare() first.")
720 logits_p = self.compute_logits(hidden_states)
721 probs = (logits_p / temperature).softmax(dim=1)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected