abelcetina's picture
Add polarity and generation API
58fc04d verified
Raw History Blame Contribute Delete
9.44 kB
"""Character-level encoder-decoder (sequence to sequence) that inverts review polarity.
Design from the course slides (Sutskever et al., 2014; Chollet's Keras character seq2seq):
one-hot characters, an encoder LSTM whose final hidden and cell states initialise a decoder
LSTM, a softmax over characters, teacher forcing during training and greedy (argmax) decoding:
1. encode the input sequence into state vectors;
2. start with a target sequence of size 1 (the start-of-sequence character);
3. feed the states and the 1-char target sequence to the decoder to predict the next character;
4. sample the next character with argmax;
5. append it to the target sequence;
6. repeat until the end-of-sequence character or the character limit.
One model serves both directions: the first input symbol is the target polarity
(`<to_negative>` or `<to_positive>`). Encoder inputs are left-padded so the last encoder step is
always the last real character; decoder targets are right-padded and padding is masked in the
loss. Inference is implemented in NumPy from the exported weights (`NumpyCharSeq2Seq`), so
serving needs neither TensorFlow nor Keras; tests check it matches the Keras model.
"""
import json
from collections import Counter
from pathlib import Path
from typing import Iterable
import numpy as np
PAD, UNK, START, END, TO_NEG, TO_POS = 0, 1, 2, 3, 4, 5
SPECIALS = ["<pad>", "<unk>", "\t", "\n", "<to_negative>", "<to_positive>"]
DIRECTION = {0: TO_NEG, 1: TO_POS}
class CharVocab:
"""Character vocabulary with the six special symbols at fixed ids."""
def __init__(self, chars: list[str]):
self.itos = SPECIALS + [c for c in chars if c not in SPECIALS]
self.stoi = {c: i for i, c in enumerate(self.itos)}
@classmethod
def build(cls, texts: Iterable[str], min_count: int = 5) -> "CharVocab":
counts = Counter()
for t in texts:
counts.update(t)
chars = sorted(c for c, n in counts.items() if n >= min_count)
return cls(chars)
def __len__(self) -> int:
return len(self.itos)
def ids(self, text: str) -> list[int]:
return [self.stoi.get(c, UNK) for c in text]
def decode(self, ids: Iterable[int]) -> str:
out = []
for i in ids:
if i == END:
break
if i >= len(SPECIALS):
out.append(self.itos[i])
return "".join(out)
def to_json(self) -> str:
return json.dumps(self.itos[len(SPECIALS):], ensure_ascii=False)
@classmethod
def from_json(cls, s: str) -> "CharVocab":
return cls(json.loads(s))
def encode_inputs(vocab: CharVocab, texts: list[str], target_labels: Iterable[int],
max_len: int) -> np.ndarray:
"""Encoder ids, shape (n, max_len + 1): direction symbol + characters, left-padded."""
out = np.full((len(texts), max_len + 1), PAD, dtype=np.int32)
for r, (t, y) in enumerate(zip(texts, target_labels)):
seq = [DIRECTION[int(y)]] + vocab.ids(t[:max_len])
out[r, -len(seq):] = seq
return out
def encode_targets(vocab: CharVocab, texts: list[str],
max_len: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Decoder input (start + chars), decoder target (chars + end) and loss mask,
each shape (n, max_len + 1), right-padded."""
n, width = len(texts), max_len + 1
dec_in = np.full((n, width), PAD, dtype=np.int32)
dec_out = np.full((n, width), PAD, dtype=np.int32)
mask = np.zeros((n, width), dtype=np.float32)
for r, t in enumerate(texts):
ids = vocab.ids(t[:max_len])
dec_in[r, :len(ids) + 1] = [START] + ids
dec_out[r, :len(ids) + 1] = ids + [END]
mask[r, :len(ids) + 1] = 1.0
return dec_in, dec_out, mask
def build_model(n_tokens: int, latent: int = 512, lr: float = 1e-3):
"""Keras training model [encoder ids, decoder ids] -> next-character probabilities."""
import keras
from keras import layers
@keras.saving.register_keras_serializable(package="amazon_reviews")
class OneHot(layers.Layer):
def __init__(self, depth: int, **kwargs):
super().__init__(**kwargs)
self.depth = depth
def call(self, x):
return keras.ops.one_hot(x, self.depth)
def get_config(self):
return {**super().get_config(), "depth": self.depth}
enc_in = keras.Input(shape=(None,), dtype="int32", name="encoder_ids")
dec_in = keras.Input(shape=(None,), dtype="int32", name="decoder_ids")
_, h, c = layers.LSTM(latent, return_state=True, name="encoder_lstm")(
OneHot(n_tokens, name="encoder_onehot")(enc_in))
seq, _, _ = layers.LSTM(latent, return_sequences=True, return_state=True,
name="decoder_lstm")(OneHot(n_tokens, name="decoder_onehot")(dec_in),
initial_state=[h, c])
probs = layers.Dense(n_tokens, activation="softmax", name="next_char")(seq)
model = keras.Model([enc_in, dec_in], probs, name="char_seq2seq")
model.compile(optimizer=keras.optimizers.Adam(learning_rate=lr),
loss="sparse_categorical_crossentropy", weighted_metrics=["accuracy"])
return model
def export_numpy(model, path: str | Path) -> Path:
"""Save the LSTM and Dense weights as a plain .npz (no pickle) for NumPy inference."""
enc, dec, dense = (model.get_layer(n) for n in ("encoder_lstm", "decoder_lstm", "next_char"))
ew, dw, ow = enc.get_weights(), dec.get_weights(), dense.get_weights()
path = Path(path)
np.savez_compressed(path, enc_kernel=ew[0], enc_rec=ew[1], enc_bias=ew[2], dec_kernel=dw[0],
dec_rec=dw[1], dec_bias=dw[2], out_w=ow[0], out_b=ow[1])
return path
def _sigmoid(x: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-x))
class NumpyCharSeq2Seq:
"""Greedy decoding with the exported weights (Keras LSTM gate order i, f, c, o)."""
def __init__(self, weights: dict[str, np.ndarray], vocab: CharVocab, max_len: int):
self.w = {k: np.asarray(v, dtype=np.float32) for k, v in weights.items()}
self.vocab = vocab
self.max_len = max_len
self.units = self.w["enc_rec"].shape[0]
@classmethod
def load(cls, directory: str | Path) -> "NumpyCharSeq2Seq":
d = Path(directory)
cfg = json.loads((d / "config.json").read_text(encoding="utf-8"))
vocab = CharVocab.from_json((d / "vocab.json").read_text(encoding="utf-8"))
with np.load(d / "weights.npz", allow_pickle=False) as z:
weights = {k: z[k] for k in z.files}
return cls(weights, vocab, cfg["max_len"])
def _step(self, prefix: str, tokens: np.ndarray, h: np.ndarray, c: np.ndarray):
w = self.w
z = w[f"{prefix}_kernel"][tokens] + h @ w[f"{prefix}_rec"] + w[f"{prefix}_bias"]
u = self.units
i, f = _sigmoid(z[:, :u]), _sigmoid(z[:, u:2 * u])
g, o = np.tanh(z[:, 2 * u:3 * u]), _sigmoid(z[:, 3 * u:])
c = f * c + i * g
return o * np.tanh(c), c
def encode(self, enc_ids: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
n = enc_ids.shape[0]
h = np.zeros((n, self.units), dtype=np.float32)
c = np.zeros_like(h)
for t in range(enc_ids.shape[1]):
h, c = self._step("enc", enc_ids[:, t], h, c)
return h, c
def generate(self, texts: list[str], target_labels: Iterable[int],
max_new: int | None = None) -> list[str]:
"""Greedy argmax decoding, batched; stops at the end symbol or the character limit."""
max_new = max_new or self.max_len
enc_ids = encode_inputs(self.vocab, texts, target_labels, self.max_len)
h, c = self.encode(enc_ids)
n = len(texts)
token = np.full(n, START, dtype=np.int64)
done = np.zeros(n, dtype=bool)
out = [[] for _ in range(n)]
for _ in range(max_new):
h, c = self._step("dec", token, h, c)
logits = h @ self.w["out_w"] + self.w["out_b"]
token = logits.argmax(axis=1)
for r in np.flatnonzero(~done):
if token[r] == END:
done[r] = True
else:
out[r].append(int(token[r]))
if done.all():
break
return [self.vocab.decode(o) for o in out]
def teacher_forced_probs(self, enc_ids: np.ndarray, dec_in: np.ndarray) -> np.ndarray:
"""Next-character distributions with teacher forcing (used in tests)."""
h, c = self.encode(enc_ids)
steps = []
for t in range(dec_in.shape[1]):
h, c = self._step("dec", dec_in[:, t], h, c)
logits = h @ self.w["out_w"] + self.w["out_b"]
e = np.exp(logits - logits.max(axis=1, keepdims=True))
steps.append(e / e.sum(axis=1, keepdims=True))
return np.stack(steps, axis=1)
def save_artifacts(model, vocab: CharVocab, config: dict, directory: str | Path) -> Path:
"""Weights for Keras (.weights.h5), NumPy weights (.npz), vocabulary and config."""
d = Path(directory)
d.mkdir(parents=True, exist_ok=True)
model.save_weights(d / "model.weights.h5")
export_numpy(model, d / "weights.npz")
(d / "vocab.json").write_text(vocab.to_json(), encoding="utf-8")
(d / "config.json").write_text(json.dumps(config, indent=2), encoding="utf-8")
return d