Datasets:
Modalities:
Text
Formats:
json
Languages:
English
Size:
< 1K
Tags:
reinforcement-learning
policy-optimization
klpo
exact-moment-replay
score-centering
stratified-sampling
License:
File size: 2,563 Bytes
f95cbd4 | 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 | """Small locally initialized models for reproducible CPU smoke experiments."""
import torch
from torch import nn
class TinyCausalLM(nn.Module):
def __init__(self, vocab_size: int = 16, width: int = 32, max_length: int = 32):
super().__init__()
self.vocab_size = vocab_size
self.token = nn.Embedding(vocab_size, width)
self.position = nn.Embedding(max_length, width)
layer = nn.TransformerEncoderLayer(width, 4, width*2, dropout=0., batch_first=True,
norm_first=False)
self.decoder = nn.TransformerEncoder(layer, 1, enable_nested_tensor=False)
self.norm = nn.LayerNorm(width)
self.lm_head = nn.Linear(width, vocab_size, bias=False)
# Untied head by default. Tests also cover tied output weights.
def hidden(self, input_ids: torch.Tensor) -> torch.Tensor:
t = input_ids.shape[1]
if t > self.position.num_embeddings:
raise ValueError("sequence exceeds configured maximum length")
x = self.token(input_ids) + self.position(torch.arange(t, device=input_ids.device))[None]
causal = torch.triu(torch.ones(t, t, dtype=torch.bool, device=input_ids.device), diagonal=1)
return self.norm(self.decoder(x, mask=causal))
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.lm_head(self.hidden(input_ids))
class FixedSpanCausalLM(TinyCausalLM):
"""Tiny demo with a fixed vocabulary basis and trainable latent head map.
forward() includes the adapter, so saved model inference agrees with its
collection and replay paths. The effective output head can change within
the fixed basis span, not acquire arbitrary new vocabulary directions.
"""
def __init__(self,vocab_size: int=16,width: int=32,max_length: int=8,*,trainable_span_adapter: bool=True):
super().__init__(vocab_size,width,max_length)
self.lm_head.weight.requires_grad_(False)
self.trainable_span_adapter=bool(trainable_span_adapter)
if self.trainable_span_adapter:
self.output_adapter=nn.Linear(width,width,bias=True)
with torch.no_grad():
self.output_adapter.weight.copy_(torch.eye(width));self.output_adapter.bias.zero_()
else:self.output_adapter=nn.Identity()
def latent(self,input_ids: torch.Tensor) -> torch.Tensor:
return self.output_adapter(self.hidden(input_ids))
def forward(self,input_ids: torch.Tensor) -> torch.Tensor:
return self.lm_head(self.latent(input_ids))
|