Download forecaster.py from Binamra00/refactoring-forecaster: direct link, hf CLI and curl.
- Browser
- Download file 7.64 kB
-
https://huggingface.co/Binamra00/refactoring-forecaster/resolve/main/forecaster.py
- Command line
-
hf download hf://Binamra00/refactoring-forecaster/forecaster.py
-
curl -L -o forecaster.py https://huggingface.co/Binamra00/refactoring-forecaster/resolve/main/forecaster.py
7.64 kB
| """ | |
| Load the refactoring forecaster and score one file at one release. | |
| from forecaster import load | |
| model = load(".") # the folder holding model.safetensors | |
| p = model.probability(code=[skeleton, *methods], # the file at the release | |
| history=[...], # one text per commit, newest first | |
| discourse=[...]) # one text per body/comment/review, newest first | |
| flagged = p >= model.threshold | |
| The texts must be built the way the dataset builds them (Notebook 3 of the replication package, | |
| https://github.com/Binamra00/refactoring-forecast-replication): the code view is the file's skeleton | |
| followed by its methods; a history text is | |
| "<COMMIT_MESSAGE>...</COMMIT_MESSAGE>\\n<FILE>...</FILE>\\n<REMOVED>...</REMOVED>\\n<ADDED>...</ADDED>"; | |
| a discourse text is one issue or pull-request body, comment or review. Every text must be dated | |
| before the release. | |
| The model classes below are those of notebook_4_model_CBERT_3.ipynb, so the weights load into them | |
| unchanged. Gradient checkpointing, which only training needs, is left out. | |
| """ | |
| import json | |
| import math | |
| from pathlib import Path | |
| import torch | |
| import torch.nn as nn | |
| from transformers import AutoConfig, AutoModel, AutoTokenizer | |
| HERE = Path(__file__).resolve().parent | |
| class Encoder(nn.Module): | |
| """One window -> one vector. CodeBERT: the first token's vector. Sentence-BERT: the token mean.""" | |
| def __init__(self, name, first_token): | |
| super().__init__() | |
| self.m = AutoModel.from_config(AutoConfig.from_pretrained(name)) # weights come from the checkpoint | |
| self.first_token = first_token | |
| def forward(self, ids, att): | |
| h = self.m(input_ids=ids, attention_mask=att).last_hidden_state | |
| if self.first_token: | |
| return h[:, 0] | |
| m = att.unsqueeze(-1).to(h.dtype) | |
| return (h * m).sum(1) / m.sum(1).clamp(min=1) | |
| class Pool(nn.Module): | |
| """Window vectors -> text vectors (mean) -> one vector per row (attention pooling).""" | |
| def __init__(self, hid): | |
| super().__init__() | |
| self.score = nn.Linear(hid, 1) | |
| self.empty = nn.Parameter(torch.zeros(hid)) | |
| def forward(self, h, win_text, text_row, n): | |
| h = h.float() | |
| n_text = text_row.numel() | |
| t = torch.zeros(n_text, h.size(1), device=h.device).index_add_(0, win_text, h) | |
| t = t / torch.zeros(n_text, device=h.device).index_add_( | |
| 0, win_text, torch.ones(len(win_text), device=h.device)).clamp(min=1).unsqueeze(1) | |
| s = self.score(t).squeeze(1).float() | |
| top = torch.full((n,), -1e30, device=h.device).scatter_reduce(0, text_row, s, "amax") | |
| e = torch.exp(s - top[text_row]) | |
| a = e / torch.zeros(n, device=h.device).index_add_(0, text_row, e)[text_row] | |
| v = torch.zeros(n, h.size(1), device=h.device).index_add_(0, text_row, t * a.unsqueeze(1)) | |
| has = torch.zeros(n, dtype=torch.bool, device=h.device) | |
| has[text_row] = True | |
| return torch.where(has.unsqueeze(1), v, self.empty.float().expand(n, -1)) | |
| class Forecaster(nn.Module): | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.cfg = cfg | |
| self.views = cfg["views"] | |
| self.threshold = cfg["threshold"] | |
| self.enc = nn.ModuleDict({v: Encoder(cfg["encoders"][v], first_token=(v != "discourse")) | |
| for v in self.views}) | |
| hid = self.enc[self.views[0]].m.config.hidden_size | |
| self.pool = nn.ModuleDict({v: Pool(hid) for v in self.views}) | |
| self.drop = nn.Dropout(cfg["dropout"]) | |
| self.out = nn.Linear(hid * len(self.views), 1) | |
| self.tok = {v: AutoTokenizer.from_pretrained(cfg["encoders"][v]) for v in self.views} | |
| # ------------------------------------------------------------------ texts -> windows | |
| def _windows(self, v, text): | |
| """(the text's kept length in tokens, its windows as token-id lists without special tokens). | |
| A text keeps at most kmax windows' worth of tokens; methods are ordered by that kept length, | |
| as in the notebook.""" | |
| body, step, kmax = self.cfg["body"][v], self.cfg["step"][v], self.cfg["kmax"] | |
| ids = self.tok[v](text, add_special_tokens=False)["input_ids"][:body + (kmax - 1) * step] | |
| n = 1 if len(ids) <= body else min(1 + math.ceil((len(ids) - body) / step), kmax) | |
| return len(ids), [ids[j * step: j * step + body] for j in range(n)] | |
| def _view(self, v, texts): | |
| """The windows a row reads in view v under the text budget: texts in order until `cap` windows.""" | |
| per_text = [self._windows(v, t) for t in texts if t and t.strip()] | |
| if v == "code" and len(per_text) > 2: # skeleton first, then methods, largest first | |
| per_text = [per_text[0], *sorted(per_text[1:], key=lambda x: -x[0])] | |
| per_text = [w for _, w in per_text] | |
| wins, win_text, left = [], [], self.cfg["cap"] | |
| for i, w in enumerate(per_text): | |
| if left == 0: | |
| break | |
| take = w[:left] | |
| wins += take | |
| win_text += [i] * len(take) | |
| left -= len(take) | |
| return wins, win_text | |
| def _pad(self, v, wins): | |
| tok = self.tok[v] | |
| L = max(len(w) for w in wins) + 2 | |
| ids = torch.full((len(wins), L), tok.pad_token_id, dtype=torch.long) | |
| att = torch.zeros((len(wins), L), dtype=torch.long) | |
| for i, w in enumerate(wins): | |
| ids[i, 0], ids[i, len(w) + 1] = tok.cls_token_id, tok.sep_token_id | |
| ids[i, 1:len(w) + 1] = torch.tensor(w, dtype=torch.long) | |
| att[i, :len(w) + 2] = 1 | |
| return ids, att | |
| # ------------------------------------------------------------------ scoring | |
| def logit(self, code, history, discourse, device="cpu", batch=32): | |
| """The row's log-odds of being refactored before the next release.""" | |
| self.eval() | |
| given = {"code": code, "history": history, "discourse": discourse} | |
| hid = self.out.in_features // len(self.views) | |
| parts = {} | |
| for v in self.views: | |
| wins, win_text = self._view(v, given[v]) | |
| if not wins: | |
| h = torch.zeros(0, hid, device=device) | |
| parts[v] = (h, torch.zeros(0, dtype=torch.long, device=device), | |
| torch.zeros(0, dtype=torch.long, device=device)) | |
| continue | |
| vecs = [] | |
| for i in range(0, len(wins), batch): | |
| ids, att = self._pad(v, wins[i:i + batch]) | |
| vecs.append(self.enc[v](ids.to(device), att.to(device)).float()) | |
| n_text = max(win_text) + 1 | |
| parts[v] = (torch.cat(vecs), torch.tensor(win_text, dtype=torch.long, device=device), | |
| torch.zeros(n_text, dtype=torch.long, device=device)) | |
| x = torch.cat([self.pool[v](*parts[v], 1) for v in self.views], 1) | |
| return float(self.out(self.drop(x)).squeeze()) | |
| def probability(self, code, history=(), discourse=(), device="cpu"): | |
| return 1.0 / (1.0 + math.exp(-self.logit(list(code), list(history), list(discourse), device))) | |
| def load(folder=HERE, device="cpu"): | |
| """The forecaster with its trained weights, from a folder holding config.json and model.safetensors.""" | |
| from safetensors.torch import load_file | |
| folder = Path(folder) | |
| cfg = json.loads((folder / "config.json").read_text(encoding="utf-8")) | |
| model = Forecaster(cfg) | |
| model.load_state_dict(load_file(str(folder / "model.safetensors")), strict=True) | |
| return model.to(device).eval() | |