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import torch.nn.functional as F
|
| 4 |
+
import tiktoken
|
| 5 |
+
|
| 6 |
+
###############################
|
| 7 |
+
# 1. モデル定義(必要最低限の実装)
|
| 8 |
+
###############################
|
| 9 |
+
|
| 10 |
+
# --- CausalSelfAttention, MLP, Block, GPTConfig, GPT の定義 ---
|
| 11 |
+
|
| 12 |
+
class CausalSelfAttention(nn.Module):
|
| 13 |
+
def __init__(self, config):
|
| 14 |
+
super().__init__()
|
| 15 |
+
assert config.n_embd % config.n_head == 0
|
| 16 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
| 17 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
| 18 |
+
self.n_head = config.n_head
|
| 19 |
+
self.n_embd = config.n_embd
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
B, T, C = x.size()
|
| 23 |
+
qkv = self.c_attn(x)
|
| 24 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
| 25 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
| 26 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
| 27 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
| 28 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 29 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C)
|
| 30 |
+
y = self.c_proj(y)
|
| 31 |
+
return y
|
| 32 |
+
|
| 33 |
+
class MLP(nn.Module):
|
| 34 |
+
def __init__(self, config):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
|
| 37 |
+
self.gelu = nn.GELU(approximate='tanh')
|
| 38 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
|
| 39 |
+
|
| 40 |
+
def forward(self, x):
|
| 41 |
+
x = self.c_fc(x)
|
| 42 |
+
x = self.gelu(x)
|
| 43 |
+
x = self.c_proj(x)
|
| 44 |
+
return x
|
| 45 |
+
|
| 46 |
+
class Block(nn.Module):
|
| 47 |
+
def __init__(self, config):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.ln_1 = nn.LayerNorm(config.n_embd)
|
| 50 |
+
self.attn = CausalSelfAttention(config)
|
| 51 |
+
self.ln_2 = nn.LayerNorm(config.n_embd)
|
| 52 |
+
self.mlp = MLP(config)
|
| 53 |
+
|
| 54 |
+
def forward(self, x):
|
| 55 |
+
x = x + self.attn(self.ln_1(x))
|
| 56 |
+
x = x + self.mlp(self.ln_2(x))
|
| 57 |
+
return x
|
| 58 |
+
|
| 59 |
+
# モデル設定を保持するシンプルなクラス
|
| 60 |
+
class GPTConfig:
|
| 61 |
+
def __init__(self, *, block_size, vocab_size, n_layer, n_head, n_embd):
|
| 62 |
+
self.block_size = block_size
|
| 63 |
+
self.vocab_size = vocab_size
|
| 64 |
+
self.n_layer = n_layer
|
| 65 |
+
self.n_head = n_head
|
| 66 |
+
self.n_embd = n_embd
|
| 67 |
+
|
| 68 |
+
class GPT(nn.Module):
|
| 69 |
+
def __init__(self, config):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.config = config
|
| 72 |
+
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
|
| 73 |
+
self.wpe = nn.Embedding(config.block_size, config.n_embd)
|
| 74 |
+
self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)])
|
| 75 |
+
self.ln_f = nn.LayerNorm(config.n_embd)
|
| 76 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 77 |
+
# 重み共有
|
| 78 |
+
self.wte.weight = self.lm_head.weight
|
| 79 |
+
self.apply(self._init_weights)
|
| 80 |
+
|
| 81 |
+
def _init_weights(self, module):
|
| 82 |
+
if isinstance(module, nn.Linear):
|
| 83 |
+
std = 0.02
|
| 84 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
|
| 85 |
+
if module.bias is not None:
|
| 86 |
+
torch.nn.init.zeros_(module.bias)
|
| 87 |
+
elif isinstance(module, nn.Embedding):
|
| 88 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 89 |
+
|
| 90 |
+
def forward(self, idx, targets=None):
|
| 91 |
+
B, T = idx.size()
|
| 92 |
+
assert T <= self.config.block_size, f"入力シーケンス長 {T} が block_size {self.config.block_size} を超えています"
|
| 93 |
+
pos = torch.arange(0, T, dtype=torch.long, device=idx.device)
|
| 94 |
+
pos_emb = self.wpe(pos)
|
| 95 |
+
tok_emb = self.wte(idx)
|
| 96 |
+
x = tok_emb + pos_emb
|
| 97 |
+
for block in self.blocks:
|
| 98 |
+
x = block(x)
|
| 99 |
+
x = self.ln_f(x)
|
| 100 |
+
logits = self.lm_head(x)
|
| 101 |
+
loss = None
|
| 102 |
+
if targets is not None:
|
| 103 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
| 104 |
+
return logits, loss
|
| 105 |
+
|
| 106 |
+
###############################
|
| 107 |
+
# 2. モデルのロードと推論関数の実装
|
| 108 |
+
###############################
|
| 109 |
+
|
| 110 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 111 |
+
MODEL_PATH = "model_00999.pt"
|
| 112 |
+
|
| 113 |
+
# チェックポイントから設定情報とモデルの状態をロード
|
| 114 |
+
checkpoint = torch.load(MODEL_PATH, map_location=device)
|
| 115 |
+
config = checkpoint['config']
|
| 116 |
+
if isinstance(config, dict):
|
| 117 |
+
config = GPTConfig(**config)
|
| 118 |
+
|
| 119 |
+
# モデルの生成と重みのロード
|
| 120 |
+
model = GPT(config)
|
| 121 |
+
model.load_state_dict(checkpoint['model'])
|
| 122 |
+
model.to(device)
|
| 123 |
+
model.eval()
|
| 124 |
+
|
| 125 |
+
# tiktoken を用いて GPT-2 用のエンコーダを取得
|
| 126 |
+
enc = tiktoken.get_encoding("gpt2")
|
| 127 |
+
|
| 128 |
+
def generate_text(prompt, max_length=100, top_k=50):
|
| 129 |
+
tokens = enc.encode(prompt)
|
| 130 |
+
x = torch.tensor(tokens, dtype=torch.long, device=device).unsqueeze(0)
|
| 131 |
+
with torch.no_grad():
|
| 132 |
+
while x.size(1) < max_length:
|
| 133 |
+
logits, _ = model(x)
|
| 134 |
+
logits = logits[:, -1, :]
|
| 135 |
+
probs = F.softmax(logits, dim=-1)
|
| 136 |
+
topk_probs, topk_indices = torch.topk(probs, top_k, dim=-1)
|
| 137 |
+
next_token = torch.multinomial(topk_probs, num_samples=1)
|
| 138 |
+
next_token = torch.gather(topk_indices, -1, next_token)
|
| 139 |
+
x = torch.cat((x, next_token), dim=1)
|
| 140 |
+
output = enc.decode(x[0].tolist())
|
| 141 |
+
return output
|
| 142 |
+
|
| 143 |
+
###############################
|
| 144 |
+
# 3. 推論 API のエントリーポイント
|
| 145 |
+
###############################
|
| 146 |
+
|
| 147 |
+
# Hugging Face Inference Endpoint 用に predict() 関数を定義
|
| 148 |
+
# リクエストは JSON 形式で {"prompt": "...", "max_length": 100, "top_k": 50} を想定
|
| 149 |
+
def predict(inputs):
|
| 150 |
+
prompt = inputs.get("prompt", "Hello, I'm a language model,")
|
| 151 |
+
max_length = int(inputs.get("max_length", 100))
|
| 152 |
+
top_k = int(inputs.get("top_k", 50))
|
| 153 |
+
generated = generate_text(prompt, max_length=max_length, top_k=top_k)
|
| 154 |
+
return {"generated_text": generated}
|