习题答案 08e · 基础习题集参考解答:化学序列分词、语言模型与注意力机制
先自己做一遍,再看答案。
直接阅读答案的学习效果远低于独立实现。建议至少尝试 20 分钟,卡住时先看习题里的 💡 提示,再展开本页。
展开状态只在当前浏览器标签页有效,关闭标签页后会重新折叠。
本 Notebook 提供 08e_exercises.ipynb 中全部 10 道基础习题的完整参考代码与输出结果。
习题 1 解答:化学感知的正则表达式分词与无损还原检验
In [1] · Python
import re
TOKEN_PATTERN = re.compile(
r"(\[[^\]]+]|Br|Cl|Si|Se|@@|@|\(|\)|\.|=|#|-|\+|\\\\|\/|~|[0-9]|[A-Za-z])"
)
test_molecules = [
"Brc1ccc(-c2scc3cc(Cl)sc23)s1",
"CN1C=NC2=C1C(=O)N(C(=O)N2C)C",
"O=[N+]([O-])c1ccc2[nH]ccc2c1",
]
def chem_tokenize(smiles):
return TOKEN_PATTERN.findall(smiles)
def verify_roundtrip(smiles_list):
stats = []
for s in smiles_list:
toks = chem_tokenize(s)
assert "".join(toks) == s, f"Roundtrip failed for {s}"
stats.append((len(toks), len(s)))
return stats
stats = verify_roundtrip(test_molecules)
for s, (n_tok, n_char) in zip(test_molecules, stats):
print(f"{s:32s} -> {n_tok:2d} tokens (vs. {n_char:2d} chars) | tokens: {chem_tokenize(s)}")
Out:
Brc1ccc(-c2scc3cc(Cl)sc23)s1 -> 26 tokens (vs. 28 chars) | tokens: ['Br', 'c', '1', 'c', 'c', 'c', '(', '-', 'c', '2', 's', 'c', 'c', '3', 'c', 'c', '(', 'Cl', ')', 's', 'c', '2', '3', ')', 's', '1']
CN1C=NC2=C1C(=O)N(C(=O)N2C)C -> 28 tokens (vs. 28 chars) | tokens: ['C', 'N', '1', 'C', '=', 'N', 'C', '2', '=', 'C', '1', 'C', '(', '=', 'O', ')', 'N', '(', 'C', '(', '=', 'O', ')', 'N', '2', 'C', ')', 'C']
O=[N+]([O-])c1ccc2[nH]ccc2c1 -> 19 tokens (vs. 28 chars) | tokens: ['O', '=', '[N+]', '(', '[O-]', ')', 'c', '1', 'c', 'c', 'c', '2', '[nH]', 'c', 'c', 'c', '2', 'c', '1']
习题 2 解答:起止符封装、长度填充与教师强制(Teacher Forcing)切片
In [2] · Python
import torch
mini_vocab = ["<pad>", "^", "$", "C", "=", "O", "(", ")", "c", "1", "s", "Br"]
mini_tok2idx = {t: i for i, t in enumerate(mini_vocab)}
batch_smiles = ["CC=O", "Brc1cccs1", "CC(=O)C"]
def encode_and_slice_batch(smiles_list, tok2idx, max_len=12):
pad_id = tok2idx["<pad>"]
bos_id = tok2idx["^"]
eos_id = tok2idx["$"]
rows = []
for s in smiles_list:
toks = chem_tokenize(s)[: max_len - 2]
ids = [bos_id] + [tok2idx[t] for t in toks] + [eos_id]
ids = ids + [pad_id] * (max_len - len(ids))
rows.append(ids)
X = torch.tensor(rows, dtype=torch.long)
return X[:, :-1], X[:, 1:]
x_in, y_target = encode_and_slice_batch(batch_smiles, mini_tok2idx, max_len=12)
print("x_in shape:", tuple(x_in.shape), "y_target shape:", tuple(y_target.shape))
print("First sample x_in :", x_in[0].tolist())
print("First sample y_target:", y_target[0].tolist())
Out:
x_in shape: (3, 11) y_target shape: (3, 11) First sample x_in : [1, 3, 3, 4, 5, 2, 0, 0, 0, 0, 0] First sample y_target: [3, 3, 4, 5, 2, 0, 0, 0, 0, 0, 0]
习题 3 解答:手写一阶马尔可夫(Bigram)转移概率矩阵
In [3] · Python
import numpy as np
import pandas as pd
toy_vocab = ["^", "$", "C", "O", "="]
toy_corpus = ["CCC", "COCO", "CC=O", "COCC"]
def build_bigram_matrix(corpus, vocab):
tok2i = {t: i for i, t in enumerate(vocab)}
V = len(vocab)
counts = np.zeros((V, V), dtype=np.float64)
for s in corpus:
seq = ["^"] + list(s) + ["$"]
for a, b in zip(seq[:-1], seq[1:]):
counts[tok2i[a], tok2i[b]] += 1.0
smoothed = counts + 1e-2
probs = smoothed / smoothed.sum(axis=1, keepdims=True)
return probs
P = build_bigram_matrix(toy_corpus, toy_vocab)
print("Row sums:", np.round(P.sum(axis=1), 6))
pd.DataFrame(np.round(P, 3), index=toy_vocab, columns=toy_vocab)
Out:
Row sums: [1. 1. 1. 1. 1.]
| ^ | $ | C | O | = | |
|---|---|---|---|---|---|
| ^ | 0.002 | 0.002 | 0.990 | 0.002 | 0.002 |
| $ | 0.200 | 0.200 | 0.200 | 0.200 | 0.200 |
| C | 0.001 | 0.200 | 0.399 | 0.300 | 0.100 |
| O | 0.002 | 0.496 | 0.496 | 0.002 | 0.002 |
| = | 0.010 | 0.010 | 0.010 | 0.962 | 0.010 |
习题 4 解答:追踪 nn.Embedding + nn.LSTM + nn.Linear 的张量维度
In [4] · Python
import torch
import torch.nn as nn
def trace_lstm_shapes(x, vocab_size=20, emb_dim=16, hid_dim=32, num_layers=2):
emb_layer = nn.Embedding(vocab_size, emb_dim)
lstm_layer = nn.LSTM(emb_dim, hid_dim, num_layers=num_layers, batch_first=True)
fc_layer = nn.Linear(hid_dim, vocab_size)
emb = emb_layer(x)
lstm_out, (h_n, c_n) = lstm_layer(emb)
logits = fc_layer(lstm_out)
return {
"emb_shape": tuple(emb.shape),
"lstm_out_shape": tuple(lstm_out.shape),
"h_n_shape": tuple(h_n.shape),
"logits_shape": tuple(logits.shape),
}
dummy_x = torch.randint(0, 20, (4, 10))
for k, v in trace_lstm_shapes(dummy_x).items():
print(f"{k:16s}: {v}")
Out:
emb_shape : (4, 10, 16) lstm_out_shape : (4, 10, 32) h_n_shape : (2, 4, 32) logits_shape : (4, 10, 20)
习题 5 解答:采样温度 \(T\) 对 Softmax 概率分布与信息熵的调控
In [5] · Python
import torch
import torch.nn.functional as F
sample_logits = torch.tensor([2.5, 1.2, 0.3, -0.8, -1.5])
def temperature_stats(logits, temperature):
probs = F.softmax(logits / temperature, dim=-1)
entropy = -(probs * torch.log(probs.clamp(min=1e-12))).sum()
return float(probs.max().item()), float(entropy.item())
for T in [0.5, 1.0, 2.0]:
max_p, ent = temperature_stats(sample_logits, T)
print(f"T = {T:3.1f} | Max Token Prob = {max_p:.4f} | Shannon Entropy = {ent:.4f} nats")
Out:
T = 0.5 | Max Token Prob = 0.9189 | Shannon Entropy = 0.3224 nats T = 1.0 | Max Token Prob = 0.6952 | Shannon Entropy = 0.9149 nats T = 2.0 | Max Token Prob = 0.4582 | Shannon Entropy = 1.3729 nats
习题 6 解答:计算每 Token 平均负对数似然(NLL per token)并剔除 <pad> 干扰
In [6] · Python
import torch
import torch.nn.functional as F
def sequence_nll_per_token(logits, targets, pad_id=0):
B, T, V = logits.shape
token_losses = F.cross_entropy(
logits.reshape(-1, V),
targets.reshape(-1),
ignore_index=pad_id,
reduction="none",
).reshape(B, T)
valid_counts = (targets != pad_id).sum(dim=1).clamp(min=1)
return token_losses.sum(dim=1) / valid_counts
torch.manual_seed(42)
fake_logits = torch.randn(3, 6, 10)
fake_targets = torch.tensor([[3, 4, 5, 2, 0, 0], [3, 6, 2, 0, 0, 0], [3, 4, 5, 6, 7, 2]])
nll_vals = sequence_nll_per_token(fake_logits, fake_targets, pad_id=0)
print("Per-sequence NLL per token:", nll_vals.tolist())
Out:
Per-sequence NLL per token: [3.632976531982422, 2.6190037727355957, 2.7021567821502686]
习题 7 解答:手写带因果掩码(Causal Mask)的缩放点积注意力
In [7] · Python
import math
import torch
import torch.nn.functional as F
def causal_scaled_dot_product_attention(Q, K, V):
T = Q.size(-2)
d_k = Q.size(-1)
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)
causal_mask = torch.triu(torch.ones(T, T, dtype=torch.bool, device=Q.device), diagonal=1)
scores = scores.masked_fill(causal_mask, float("-inf"))
attn_weights = F.softmax(scores, dim=-1)
output = torch.matmul(attn_weights, V)
return output, attn_weights
torch.manual_seed(7)
q_demo = torch.randn(2, 5, 8)
out_demo, w_demo = causal_scaled_dot_product_attention(q_demo, q_demo, q_demo)
print("Output shape:", tuple(out_demo.shape))
print("Upper triangle sum (strictly 0.0):", float(torch.triu(w_demo, diagonal=1).sum().item()))
print("Sample 0 attention matrix:\n", w_demo[0].round(decimals=3))
Out:
Output shape: (2, 5, 8)
Upper triangle sum (strictly 0.0): 0.0
Sample 0 attention matrix:
tensor([[1.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.0600, 0.9400, 0.0000, 0.0000, 0.0000],
[0.1370, 0.0140, 0.8490, 0.0000, 0.0000],
[0.0250, 0.0130, 0.0050, 0.9570, 0.0000],
[0.0260, 0.0260, 0.0400, 0.0330, 0.8760]])
习题 8 解答:用 RDKit 反应模板预测 Suzuki 偶联产物并做 Canonical 精确匹配评估
In [8] · Python
from rdkit import Chem
from rdkit.Chem import rdChemReactions
def run_suzuki_and_check_match(halide_smi, boronic_smi, expected_product_smi):
rxn = rdChemReactions.ReactionFromSmarts("[c:1][Br,Cl].[c:2]B(O)O>>[c:1]-[c:2]")
m1 = Chem.MolFromSmiles(halide_smi)
m2 = Chem.MolFromSmiles(boronic_smi)
prods = rxn.RunReactants((m1, m2))
if not prods:
return None, False
pred_mol = prods[0][0]
Chem.SanitizeMol(pred_mol)
pred_canon = Chem.MolToSmiles(pred_mol, canonical=True)
gold_canon = Chem.MolToSmiles(Chem.MolFromSmiles(expected_product_smi), canonical=True)
return pred_canon, (pred_canon == gold_canon)
pred_c, matched = run_suzuki_and_check_match(
"Brc1ccccc1",
"OB(O)c1cccs1",
"c1ccc(-c2cccs2)cc1", # 与标准顺序不同的写法
)
print(f"Predicted Canonical SMILES : {pred_c}")
print(f"Canonical Exact Match : {matched}")
Out:
Predicted Canonical SMILES : c1ccc(-c2cccs2)cc1 Canonical Exact Match : True
习题 9 解答:手写单步字节对编码(BPE)高频符号对统计
In [9] · Python
from collections import Counter
def most_frequent_pair(vocab):
counts = Counter()
for symbols, freq in vocab.items():
for i in range(len(symbols) - 1):
counts[(symbols[i], symbols[i + 1])] += freq
return counts.most_common(1)[0]
demo_v = {('o','x','i','d','e','</w>'): 9, ('o','x','i','d','e','s','</w>'): 6, ('p','e','r','o','x','i','d','e','</w>'): 5}
print("最高频相邻字符对:", most_frequent_pair(demo_v))
Out:
最高频相邻字符对: (('o', 'x'), 20)
习题 10 解答:材料文献 JSON 结构化抽取结果的防幻觉校验器
In [10] · Python
def verify_bandgap_extraction(abstract_text, extracted_dict):
quote = extracted_dict.get("quote", "")
eg = extracted_dict.get("bandgap_eV", None)
if not quote or quote not in abstract_text or eg is None:
return False
if not (0.0 <= float(eg) <= 15.0):
return False
return str(eg) in quote
abs_txt = "UV-vis absorption spectroscopy reveals a direct optical band gap of 4.85 eV for beta-Ga2O3."
print("真实抽取校验:", verify_bandgap_extraction(abs_txt, {"formula": "Ga2O3", "bandgap_eV": 4.85, "quote": "direct optical band gap of 4.85 eV"}))
print("幻觉抽取校验:", verify_bandgap_extraction(abs_txt, {"formula": "Ga2O3", "bandgap_eV": 3.20, "quote": "direct optical band gap of 3.20 eV"}))
Out:
真实抽取校验: True 幻觉抽取校验: False