SetCon / modeling_setcon_lm.py
lschiweck's picture
Add SetCon-LM: language model on the frozen encoder (three seeds) (#1)
8e49cd2
Raw History Blame Contribute Delete
16.6 kB
"""SetCon-LM: Qwen3.5-0.8B answering questions about IMU windows, on top of the frozen SetCon encoder (Hugging Face
remote code, inference only, transformers >= 5).
setcon = AutoModel.from_pretrained("<repo>", trust_remote_code=True) # encoder, seed 1
lm = AutoModel.from_pretrained("<repo>", subfolder="lm", trust_remote_code=True) # its language model
lm.ask(setcon, windows, "What is the person doing?")
Seeds 2 and 3: encoder subfolder="seed2" with LM subfolder="lm/seed2" (and the same for seed 3). Each LM was trained
on one encoder checkpoint and refuses another one.
How a window reaches the language model (paper Sec. 3.6):
1. The windows carry the setup reference of their device in channels 6-8, as for zero-shot classification
(processing_setcon.set_reference with SetConModel.estimate_reference on six unlabeled windows of the device).
2. The frozen encoder runs once. Its setup vector (a linear map of the worn-site and gyroscope flags) gives one
token, and every worn site x valid 0.2-s patch gives one token (at most 1 + 22 x 50).
3. The projector maps each to the LM's width: two-layer MLP, plus learned site, patch-time and token-type
embeddings for the patch tokens, then LayerNorm and a learned scale.
4. These vectors precede the chat prompt: the system prompt, then "Sensors worn at: <sites>." and the question
(Qwen3.5 chat template, thinking off).
5. Greedy decoding stops at <|im_end|> or <|endoftext|>.
Settings of the paper's evaluation: encoder and projector under bfloat16 autocast on CUDA, the language model in
float32 without autocast, batches of 32 windows (left padding), at most 48 new tokens.
"""
from __future__ import annotations
import os
os.environ.setdefault("FLA_DISABLE_BACKEND_DISPATCH", "1") # see configuration_setcon_lm.py; before fla is imported
import numpy as np # noqa: E402
import torch # noqa: E402
import torch.nn as nn # noqa: E402
import torch.nn.functional as F # noqa: E402
from transformers import PreTrainedModel, Qwen2Tokenizer # noqa: E402
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5ForCausalLM # noqa: E402
from .configuration_setcon_lm import SetConLMConfig # noqa: E402
from .processing_setcon import place_devices # noqa: E402
CE_CHUNK = 256 # answer positions per vocabulary projection when scoring candidates (as in training)
def _mlp(d_in, d_out):
return nn.Sequential(nn.Linear(d_in, d_out), nn.GELU(), nn.Linear(d_out, d_out))
class SetConProjector(nn.Module):
"""Encoder features of one window -> LM input vectors: the setup token, then one token per worn site and valid
patch (sites in index order, patches in time order within each site)."""
def __init__(self, encoder_dim, lm_dim, num_sites, num_patches):
super().__init__()
self.setup_mlp = _mlp(encoder_dim, lm_dim)
self.patch_mlp = _mlp(encoder_dim, lm_dim)
self.site_embedding = nn.Embedding(num_sites, lm_dim)
self.time_embedding = nn.Embedding(num_patches, lm_dim)
self.token_type_embedding = nn.Embedding(2, lm_dim) # 0 = setup token, 1 = patch token
self.norm = nn.LayerNorm(lm_dim)
self.scale = nn.Parameter(torch.tensor(0.02))
def forward(self, setup, tokens, worn, patch_valid):
"""setup (encoder_dim), tokens (sites, patches, encoder_dim), worn (sites) bool, patch_valid (patches) bool
-> (1 + worn sites x valid patches, lm_dim)."""
sites = torch.nonzero(worn, as_tuple=False).flatten()
patches = torch.nonzero(patch_valid, as_tuple=False).flatten()
first = self.setup_mlp(setup)[None] + self.token_type_embedding.weight[0][None]
x = self.patch_mlp(tokens[sites][:, patches]) + self.site_embedding(sites)[:, None] + \
self.time_embedding(patches)[None, :] + self.token_type_embedding.weight[1]
out = torch.cat([first, x.reshape(-1, x.shape[-1])], dim=0)
return self.norm(out) * self.scale
@torch.no_grad()
def encoder_tokens(setcon, x, worn, gyro, patch_valid):
"""The frozen encoder's setup vector (B, 256) and patch tokens (B, 22, 50, 256; zero where no site is worn or a
patch is invalid), read from its own forward pass under bfloat16 autocast on CUDA, as float32."""
enc = setcon.encoder
got = {}
hooks = [enc.setup_embed.register_forward_hook(lambda m, i, o: got.__setitem__("setup", o)),
enc.final_norm.register_forward_hook(lambda m, i, o: got.__setitem__("tokens", o))]
try:
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=x.is_cuda):
enc(x, worn, gyro, patch_valid)
finally:
for h in hooks:
h.remove()
observed = worn[:, :, None] & patch_valid[:, None, :]
return got["setup"].float(), got["tokens"].masked_fill(~observed[..., None], 0).float()
class SetConLM(PreTrainedModel):
"""Projector + Qwen3.5-0.8B (fine-tuned). Use `ask` for free answers; `choose` and `yes_no` score given answers
by likelihood, the way the paper reads its candidate questions."""
config_class = SetConLMConfig
base_model_prefix = "setcon_lm"
main_input_name = "inputs_embeds"
_tied_weights_keys = {"lm.lm_head.weight": "lm.model.embed_tokens.weight"}
def __init__(self, config: SetConLMConfig):
super().__init__(config)
self.projector = SetConProjector(config.encoder_hidden_size, config.text_config.hidden_size, config.num_sites,
config.num_patches)
self.lm = Qwen3_5ForCausalLM(config.text_config)
self.tokenizer = None
self.post_init()
def _init_weights(self, module):
"""Weights always come from a checkpoint."""
def get_input_embeddings(self):
return self.lm.get_input_embeddings()
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
"""Also loads the tokenizer (with the chat template) stored next to the weights."""
model = super().from_pretrained(pretrained_model_name_or_path, *args, **kwargs)
hub = {k: kwargs[k] for k in ("subfolder", "revision", "cache_dir", "token", "local_files_only",
"force_download", "proxies") if kwargs.get(k) is not None}
model.tokenizer = Qwen2Tokenizer.from_pretrained(pretrained_model_name_or_path, **hub)
return model
# ---------------------------------------------------------------- inputs
def _check_encoder(self, setcon):
seed = getattr(setcon.config, "training_seed", None)
if seed != self.config.encoder_training_seed:
k = self.config.encoder_training_seed
raise ValueError(f"this language model was trained on SetCon seed {k}, the encoder given is seed {seed}; "
f"load the encoder with " + ("no subfolder" if k == 1 else f"subfolder='seed{k}'"))
@staticmethod
def encoder_inputs(setcon, windows):
"""windows: (N, 200, 22, 9) or (200, 22, 9) model windows with the reference channels set, or
{site name: (N, 200, 9)} of devices worn together, or a tuple (x, worn, gyro, patch_valid) of prepared
encoder inputs as returned by SetConModel.encoder_inputs. Returns that tuple (CPU tensors)."""
if isinstance(windows, tuple) and len(windows) == 4 and np.ndim(windows[1]) == 2:
return tuple(torch.as_tensor(t) for t in windows)
if isinstance(windows, dict):
windows = place_devices(windows)
w = np.asarray(windows, dtype=np.float32)
if w.ndim == 3:
w = w[None]
return setcon.encoder_inputs(torch.from_numpy(np.ascontiguousarray(w)))
@torch.no_grad()
def prefixes(self, setcon, x, worn, gyro, patch_valid):
"""LM input vectors of a batch of windows (one tensor per window, float32 on the LM's device)."""
dev = next(setcon.encoder.parameters()).device
x, worn, gyro, patch_valid = (t.to(dev) for t in (x, worn, gyro, patch_valid))
setup, tokens = encoder_tokens(setcon, x, worn, gyro, patch_valid)
lm_dev = self.device
setup, tokens, worn, patch_valid = (t.to(lm_dev) for t in (setup, tokens, worn, patch_valid))
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=setup.is_cuda):
return [self.projector(setup[i], tokens[i], worn[i], patch_valid[i]) for i in range(len(setup))]
def worn_line(self, worn):
sites = [self.config.site_text[j] for j in np.flatnonzero(np.asarray(worn))]
return "Sensors worn at: " + ", ".join(sites) + "."
def prompt_ids(self, worn, question):
"""Chat prompt token ids: system prompt, then the worn-site line and the question as the user turn."""
msgs = [{"role": "system", "content": self.config.system_prompt},
{"role": "user", "content": self.worn_line(worn) + "\n" + question}]
out = self.tokenizer.apply_chat_template(msgs, add_generation_prompt=True, tokenize=True,
enable_thinking=False)
if hasattr(out, "keys") and "input_ids" in out.keys():
out = out["input_ids"]
out = list(out)
if out and isinstance(out[0], (list, tuple)):
out = list(out[0])
return out
def _token_id(self, text):
return self.tokenizer.convert_tokens_to_ids(text)
def _questions(self, question, n):
q = self.config.default_question if question is None else question
q = [q] * n if isinstance(q, str) else list(q)
if len(q) != n:
raise ValueError(f"{len(q)} questions for {n} windows")
return q
# ---------------------------------------------------------------- free answers
@torch.no_grad()
def generate_answers(self, prefixes, prompts, max_new_tokens=None):
"""Greedy answers for one batch: [prefix | prompt] left-padded. Returns dicts (text, token_ids, stopped)."""
max_new_tokens = max_new_tokens or self.config.max_new_tokens
embed = self.lm.get_input_embeddings()
dev = self.device
seqs = []
for k, pid in enumerate(prompts):
e = embed(torch.tensor(pid, device=dev))
seqs.append(e if prefixes is None else torch.cat([prefixes[k].to(e.dtype), e], 0))
L = max(s.shape[0] for s in seqs)
inp = torch.zeros(len(seqs), L, seqs[0].shape[-1], dtype=seqs[0].dtype, device=dev)
mask = torch.zeros(len(seqs), L, dtype=torch.long, device=dev)
for i, s in enumerate(seqs):
inp[i, L - s.shape[0]:] = s
mask[i, L - s.shape[0]:] = 1
stop = [self._token_id(t) for t in self.config.stop_tokens]
out = self.lm.generate(inputs_embeds=inp, attention_mask=mask, max_new_tokens=max_new_tokens,
do_sample=False, eos_token_id=stop, pad_token_id=self._token_id("<|endoftext|>"))
res = []
for r in out.tolist():
cut = next((j for j, t in enumerate(r) if t in stop), len(r))
res.append(dict(text=self.tokenizer.decode(r[:cut], skip_special_tokens=True).strip(),
token_ids=r[:cut + 1] if cut < len(r) else r, stopped=cut < len(r)))
return res
@torch.no_grad()
def ask(self, setcon, windows, question=None, batch_size=None, max_new_tokens=None, return_details=False):
"""Free answer to `question` (one string for all windows, or one per window; default "What is the person
doing?") for every window. Returns a list of strings, or of dicts (text, token_ids, stopped)."""
self._check_encoder(setcon)
x, worn, gyro, pv = self.encoder_inputs(setcon, windows)
qs = self._questions(question, len(x))
bs = batch_size or self.config.batch_size
res = []
for lo in range(0, len(x), bs):
sl = slice(lo, min(len(x), lo + bs))
pres = self.prefixes(setcon, x[sl], worn[sl], gyro[sl], pv[sl])
pids = [self.prompt_ids(worn[i].numpy(), qs[i]) for i in range(sl.start, sl.stop)]
res += self.generate_answers(pres, pids, max_new_tokens)
return res if return_details else [r["text"] for r in res]
# ---------------------------------------------------------------- scoring given answers
@torch.no_grad()
def answer_nll(self, prefix, prompt, answers):
"""Mean negative log-likelihood per token of each answer (its tokens + <|im_end|>) after [prefix | prompt]."""
embed = self.lm.get_input_embeddings()
dev = self.device
end_id = self._token_id("<|im_end|>")
seqs, labels = [], []
for ans in answers:
e = embed(torch.tensor(prompt, device=dev))
aid = torch.tensor(self.tokenizer(ans, add_special_tokens=False)["input_ids"] + [end_id], device=dev)
n_p = 0 if prefix is None else prefix.shape[0]
parts = ([] if prefix is None else [prefix.to(e.dtype)]) + [e, embed(aid)]
seqs.append(torch.cat(parts, 0))
labels.append(torch.cat([torch.full((n_p + e.shape[0],), -100, dtype=torch.long, device=dev), aid]))
L = max(s.shape[0] for s in seqs)
inp = torch.zeros(len(seqs), L, seqs[0].shape[-1], dtype=seqs[0].dtype, device=dev)
mask = torch.zeros(len(seqs), L, dtype=torch.long, device=dev)
lab = torch.full((len(seqs), L), -100, dtype=torch.long, device=dev)
for i, (s, l_) in enumerate(zip(seqs, labels)):
inp[i, :s.shape[0]] = s
mask[i, :s.shape[0]] = 1
lab[i, :l_.shape[0]] = l_
hs = self.lm.model(inputs_embeds=inp, attention_mask=mask).last_hidden_state
tgt = lab[:, 1:]
m = tgt != -100
hsel, tsel = hs[:, :-1][m], tgt[m]
ce = torch.cat([F.cross_entropy(self.lm.lm_head(hsel[c:c + CE_CHUNK]).float(), tsel[c:c + CE_CHUNK],
reduction="none") for c in range(0, hsel.shape[0], CE_CHUNK)])
full = torch.zeros(tgt.shape, dtype=ce.dtype, device=dev)
full[m] = ce
mf = m.float()
return ((full * mf).sum(1) / mf.sum(1).clamp(min=1.0)).cpu().tolist()
@torch.no_grad()
def choose(self, setcon, windows, question, candidates):
"""Pick one of the candidate answers per window by the lowest mean token NLL (paper: the five-way questions
and the four-way activity choice). candidates: one list for all windows or one list per window.
Returns dicts (index, nll)."""
self._check_encoder(setcon)
x, worn, gyro, pv = self.encoder_inputs(setcon, windows)
qs = self._questions(question, len(x))
per_window = len(candidates) == len(x) and all(isinstance(c, (list, tuple)) for c in candidates)
res = []
for i in range(len(x)):
pre = self.prefixes(setcon, x[i:i + 1], worn[i:i + 1], gyro[i:i + 1], pv[i:i + 1])[0]
nll = self.answer_nll(pre, self.prompt_ids(worn[i].numpy(), qs[i]),
candidates[i] if per_window else candidates)
res.append(dict(index=int(np.argmin(nll)), nll=nll))
return res
@torch.no_grad()
def yes_no(self, setcon, windows, question):
"""Yes/no question per window: log P("Yes") and log P("No") as the first answer token.
Returns dicts (answer 'yes' or 'no', log_p_yes, log_p_no)."""
self._check_encoder(setcon)
x, worn, gyro, pv = self.encoder_inputs(setcon, windows)
qs = self._questions(question, len(x))
yes = self.tokenizer("Yes", add_special_tokens=False)["input_ids"][0]
no = self.tokenizer("No", add_special_tokens=False)["input_ids"][0]
embed = self.lm.get_input_embeddings()
res = []
for i in range(len(x)):
pre = self.prefixes(setcon, x[i:i + 1], worn[i:i + 1], gyro[i:i + 1], pv[i:i + 1])[0]
e = embed(torch.tensor(self.prompt_ids(worn[i].numpy(), qs[i]), device=self.device))
inp = torch.cat([pre.to(e.dtype), e], 0)[None]
hs = self.lm.model(inputs_embeds=inp, attention_mask=torch.ones(1, inp.shape[1], dtype=torch.long,
device=self.device)).last_hidden_state
lp = F.log_softmax(self.lm.lm_head(hs[:, -1]).float(), -1)[0]
ly, ln = float(lp[yes]), float(lp[no])
res.append(dict(answer="yes" if ly > ln else "no", log_p_yes=ly, log_p_no=ln))
return res