MCPcopy Create free account
hub / github.com/Standard-Intelligence/hertz-dev / Stack

Class Stack

transformer.py:323–381  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

321
322@si_module
323class Stack(nn.Module):
324 class Config:
325 layers: int
326 dim: int
327 seq_len: int
328 n_head: int = 32
329 ff_dim: int = None
330 kv_heads: int = None
331 eps: float = 1e-5
332 theta: Union[int, float] = 10_000
333 causal: bool = True
334
335 from_pretrained: Optional[Tuple[str, int]] = None
336
337 def __init__(self, c: Config):
338 super().__init__()
339
340 from_pretrained = c.from_pretrained
341 if exists(from_pretrained):
342 checkpoint = load_ckpt(c.from_pretrained)
343
344 self.shape_rotator = ShapeRotator(c.dim//c.n_head, c.seq_len, theta=c.theta)
345
346 self.layers = nn.ModuleList([
347 Block(
348 dim=c.dim,
349 layer_id=l,
350 n_head=c.n_head,
351 kv_heads=c.kv_heads,
352 ff_dim=c.ff_dim,
353 eps=c.eps,
354 causal=c.causal,
355 shape_rotator=self.shape_rotator,
356 ) for l in range(c.layers)
357 ])
358
359 kv_heads = c.kv_heads or c.n_head
360 head_dim = c.dim // c.n_head
361 cache_shape = [c.layers, c.seq_len, 2, kv_heads, head_dim]
362 self.cache_shape = cache_shape
363 self.cache = [None] * c.layers
364
365 if exists(from_pretrained):
366 self.load_state_dict(checkpoint)
367
368 def init_cache(self, bsize, device, dtype, length:int=None):
369 if self.cache_shape is None:
370 return
371 cache_shape = self.cache_shape.copy()
372 cache_shape[1] = length or cache_shape[1]
373 self.cache = T.full((bsize, *cache_shape), CACHE_FILL_VALUE, device=device, dtype=dtype).transpose(0, 1)
374
375 def deinit_cache(self):
376 self.cache = [None] * len(self.cache)
377
378 def forward(self, x: Tensor) -> Tensor:
379 for l, layer in enumerate(self.layers):
380 x = layer(x, kv=self.cache[l])

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected