MCPcopy Create free account
hub / github.com/Pints-AI/1.5-Pints / build_rope_cache

Function build_rope_cache

lit_gpt/model.py:435–466  ·  view source on GitHub ↗

Enhanced Transformer with Rotary Position Embedding. Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/ transformers/rope/__init__.py. MIT License: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/mas

(
    seq_len: int,
    n_elem: int,
    dtype: torch.dtype,
    device: torch.device,
    base: int = 10000,
    condense_ratio: int = 1,
)

Source from the content-addressed store, hash-verified

433
434
435def build_rope_cache(
436 seq_len: int,
437 n_elem: int,
438 dtype: torch.dtype,
439 device: torch.device,
440 base: int = 10000,
441 condense_ratio: int = 1,
442) -> RoPECache:
443 """Enhanced Transformer with Rotary Position Embedding.
444
445 Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
446 transformers/rope/__init__.py. MIT License:
447 https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
448 """
449 # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
450 theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, device=device) / n_elem))
451
452 # Create position indexes `[0, 1, ..., seq_len - 1]`
453 seq_idx = torch.arange(seq_len, device=device) / condense_ratio
454
455 # Calculate the product of position index and $\theta_i$
456 idx_theta = torch.outer(seq_idx, theta)
457
458 cos, sin = torch.cos(idx_theta), torch.sin(idx_theta)
459
460 # added by peiyuan to ensure same data type with q, k, to use fused rotary embedding
461 if dtype == torch.bfloat16:
462 return cos.bfloat16(), sin.bfloat16()
463 # this is to mimic the behaviour of complex32, else we will get different results
464 if dtype in (torch.float16, torch.bfloat16, torch.int8):
465 return cos.half(), sin.half()
466 return cos, sin
467
468
469def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:

Callers 2

get_rope_cacheMethod · 0.85
build_rope_cacheMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected