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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#%%
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 5 |
+
from pprint import pprint
|
| 6 |
+
|
| 7 |
+
#%%
|
| 8 |
+
|
| 9 |
+
model_name="mistralai/Mistral-7B-v0.1"
|
| 10 |
+
|
| 11 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 12 |
+
# model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16)
|
| 13 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 14 |
+
|
| 15 |
+
# Move the model to GPU if available
|
| 16 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 17 |
+
model.to(device)
|
| 18 |
+
|
| 19 |
+
#%%
|
| 20 |
+
|
| 21 |
+
input_text = "I just drive to the store to but eggs, but they had some."
|
| 22 |
+
input_text = "He asked me to prostate myself before the king, but I rifused."
|
| 23 |
+
input_text = "He asked me to prostrate myself before the king, but I rifused."
|
| 24 |
+
|
| 25 |
+
#%%
|
| 26 |
+
inputs = tokenizer(input_text, return_tensors="pt").to(device)
|
| 27 |
+
input_ids = inputs["input_ids"]
|
| 28 |
+
labels = input_ids
|
| 29 |
+
|
| 30 |
+
#%%
|
| 31 |
+
with torch.no_grad():
|
| 32 |
+
outputs = model(**inputs, labels=labels)
|
| 33 |
+
|
| 34 |
+
#%%
|
| 35 |
+
|
| 36 |
+
# Get logits and shift them
|
| 37 |
+
logits = outputs.logits[0, :-1, :]
|
| 38 |
+
|
| 39 |
+
# Calculate log probabilities
|
| 40 |
+
log_probs = torch.log_softmax(logits, dim=-1)
|
| 41 |
+
|
| 42 |
+
# Get the log probability of each token in the sequence
|
| 43 |
+
token_log_probs = log_probs[range(log_probs.shape[0]), input_ids[0][1:]]
|
| 44 |
+
|
| 45 |
+
# Decode tokens and pair them with their log probabilities
|
| 46 |
+
tokens = tokenizer.convert_ids_to_tokens(input_ids[0])
|
| 47 |
+
result = list(zip(tokens[1:], token_log_probs.tolist()))
|
| 48 |
+
|
| 49 |
+
#%%
|
| 50 |
+
for token, logprob in result:
|
| 51 |
+
print(f"Token: {token}, Log Probability: {logprob:.4f}")
|
| 52 |
+
|
| 53 |
+
# %%
|
| 54 |
+
words = []
|
| 55 |
+
current_word = []
|
| 56 |
+
current_log_probs = []
|
| 57 |
+
|
| 58 |
+
for token, logprob in result:
|
| 59 |
+
if not token.startswith(chr(9601)) and token.isalpha():
|
| 60 |
+
current_word.append(token)
|
| 61 |
+
current_log_probs.append(logprob)
|
| 62 |
+
else:
|
| 63 |
+
if current_word:
|
| 64 |
+
words.append(("".join(current_word), sum(current_log_probs)))
|
| 65 |
+
current_word = [token]
|
| 66 |
+
current_log_probs = [logprob]
|
| 67 |
+
|
| 68 |
+
if current_word:
|
| 69 |
+
words.append(("".join(current_word), sum(current_log_probs)))
|
| 70 |
+
|
| 71 |
+
for word, avg_logprob in words:
|
| 72 |
+
print(f"Word: {word}, Log Probability: {avg_logprob:.4f}")
|
| 73 |
+
|
| 74 |
+
# %%
|
| 75 |
+
|
| 76 |
+
@dataclass
|
| 77 |
+
class Word:
|
| 78 |
+
tokens: list[int]
|
| 79 |
+
text: str
|
| 80 |
+
logprob: float
|
| 81 |
+
first_token_index: int
|
| 82 |
+
|
| 83 |
+
def split_into_words(tokens, log_probs) -> list[Word]:
|
| 84 |
+
words = []
|
| 85 |
+
current_word = []
|
| 86 |
+
current_log_probs = []
|
| 87 |
+
current_word_first_token_index = 0
|
| 88 |
+
|
| 89 |
+
for i, (token, logprob) in enumerate(zip(tokens, log_probs)):
|
| 90 |
+
if not token.startswith(chr(9601)) and token.isalpha():
|
| 91 |
+
current_word.append(token)
|
| 92 |
+
current_log_probs.append(logprob)
|
| 93 |
+
else:
|
| 94 |
+
if current_word:
|
| 95 |
+
words.append(Word(current_word, "".join(current_word), sum(current_log_probs), current_word_first_token_index))
|
| 96 |
+
current_word = [token]
|
| 97 |
+
current_log_probs = [logprob]
|
| 98 |
+
current_word_first_token_index = i
|
| 99 |
+
|
| 100 |
+
if current_word:
|
| 101 |
+
words.append(Word(current_word, "".join(current_word), sum(current_log_probs), current_word_first_token_index))
|
| 102 |
+
|
| 103 |
+
return words
|
| 104 |
+
|
| 105 |
+
words = split_into_words(tokens[1:], token_log_probs)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
#%%
|
| 109 |
+
def generate_replacements(model, tokenizer, prefix, num_samples=5):
|
| 110 |
+
input_context = tokenizer(prefix, return_tensors="pt").to(device)
|
| 111 |
+
input_ids = input_context["input_ids"]
|
| 112 |
+
|
| 113 |
+
new_words = []
|
| 114 |
+
for _ in range(num_samples):
|
| 115 |
+
with torch.no_grad():
|
| 116 |
+
outputs = model.generate(
|
| 117 |
+
input_ids=input_ids,
|
| 118 |
+
max_length=input_ids.shape[-1] + 5, # generate a few tokens beyond the prefix
|
| 119 |
+
num_return_sequences=1,
|
| 120 |
+
temperature=1.0,
|
| 121 |
+
top_k=50, # use top-k sampling
|
| 122 |
+
top_p=0.95, # use nucleus sampling
|
| 123 |
+
do_sample=True
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
generated_ids = outputs[0][input_ids.shape[-1]:] # extract the newly generated part
|
| 127 |
+
new_word = tokenizer.decode(generated_ids, skip_special_tokens=True).split()[0]
|
| 128 |
+
new_words.append(new_word)
|
| 129 |
+
|
| 130 |
+
return new_words
|
| 131 |
+
|
| 132 |
+
# Generate new words for low probability words
|
| 133 |
+
for word in low_prob_words:
|
| 134 |
+
prefix_index = word.first_token_index
|
| 135 |
+
prefix_tokens = tokens[:prefix_index + 1] # include the word itself
|
| 136 |
+
prefix = tokenizer.convert_tokens_to_string(prefix_tokens)
|
| 137 |
+
|
| 138 |
+
replacements = generate_replacements(model, tokenizer, prefix)
|
| 139 |
+
|
| 140 |
+
print(f"Original word: {word.text}, Log Probability: {word.logprob:.4f}")
|
| 141 |
+
print(f"Proposed replacements: {replacements}")
|
| 142 |
+
print()
|
| 143 |
+
|
| 144 |
+
# %%
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
openai
|
| 2 |
+
ipykernel
|
| 3 |
+
ipywidgets
|
| 4 |
+
# pyzmq==25.1.2
|
| 5 |
+
notebook
|
| 6 |
+
transformers
|
| 7 |
+
torch
|
| 8 |
+
huggingface_hub
|
shell.nix
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
let
|
| 2 |
+
|
| 3 |
+
nixpkgs = import <nixpkgs> {};
|
| 4 |
+
pkgs = nixpkgs.pkgs;
|
| 5 |
+
|
| 6 |
+
in
|
| 7 |
+
|
| 8 |
+
pkgs.mkShell {
|
| 9 |
+
shellHook = ''
|
| 10 |
+
export LD_LIBRARY_PATH=${pkgs.stdenv.cc.cc.lib}/lib/
|
| 11 |
+
'';
|
| 12 |
+
}
|