Download src/probe.py from ShubhamOza/chrono-lookahead-replication: direct link, hf CLI and curl.
- Browser
- Download file 1.87 kB
-
https://huggingface.co/ShubhamOza/chrono-lookahead-replication/resolve/main/src/probe.py
- Command line
-
hf download hf://ShubhamOza/chrono-lookahead-replication/src/probe.py
-
curl -L -o probe.py https://huggingface.co/ShubhamOza/chrono-lookahead-replication/resolve/main/src/probe.py
1.87 kB
| """A small memorisation probe with the masked language model head. | |
| For the largest next day moves in the sample, build a sentence such as | |
| "AMD stock [MASK] on May 3, 2023." and ask a ChronoBERT vintage whether the | |
| blank is more likely an up word or a down word. A vintage trained before the | |
| event cannot know the answer. If a vintage trained after the event does much | |
| better, it has picked up the outcome during pre-training. | |
| """ | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| from transformers import AutoModelForMaskedLM, AutoTokenizer | |
| UP = ["rose", "gained", "jumped", "surged", "climbed", "rallied"] | |
| DOWN = ["fell", "dropped", "slid", "plunged", "tumbled", "sank"] | |
| def build_prompts(sample, n_events): | |
| big = sample.loc[sample["ret_next"].abs().nlargest(n_events).index].copy() | |
| return big | |
| def single_token_ids(tok, words): | |
| ids = [] | |
| for w in words: | |
| t = tok(" " + w, add_special_tokens=False)["input_ids"] | |
| if len(t) == 1: | |
| ids.append(t[0]) | |
| return ids | |
| def up_probability(events, model_id, trade_dates): | |
| """Share of probability on up words, among up and down words, per event.""" | |
| tok = AutoTokenizer.from_pretrained(model_id) | |
| model = AutoModelForMaskedLM.from_pretrained(model_id, attn_implementation="sdpa").eval() | |
| up_ids, down_ids = single_token_ids(tok, UP), single_token_ids(tok, DOWN) | |
| out = [] | |
| for (_, row), day in zip(events.iterrows(), trade_dates): | |
| text = f"{row['ticker']} stock {tok.mask_token} on {day:%B} {day.day}, {day.year}." | |
| enc = tok(text, return_tensors="pt") | |
| pos = (enc["input_ids"][0] == tok.mask_token_id).nonzero()[0, 0] | |
| p = model(**enc).logits[0, pos].softmax(-1) | |
| up, down = p[up_ids].sum().item(), p[down_ids].sum().item() | |
| out.append(up / (up + down)) | |
| del model | |
| return np.array(out) | |