jacobrenn commited on
Commit
b9dc6ba
1 Parent(s): 38782ac

Upload instruct_pipeline.py

Browse files
Files changed (1) hide show
  1. instruct_pipeline.py +160 -0
instruct_pipeline.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+ from transformers import Pipeline, PreTrainedTokenizer
5
+
6
+
7
+ INSTRUCTION_KEY = "### Instruction:"
8
+ RESPONSE_KEY = "### Response:"
9
+ END_KEY = "### End"
10
+ INTRO_BLURB = (
11
+ "Below is an instruction that describes a task. Write a response that appropriately completes the request."
12
+ )
13
+
14
+ # This is the prompt that is used for generating responses using an already trained model. It ends with the response
15
+ # key, where the job of the model is to provide the completion that follows it (i.e. the response itself).
16
+ PROMPT_FOR_GENERATION_FORMAT = """{intro}
17
+
18
+ {instruction_key}
19
+ {instruction}
20
+
21
+ {response_key}
22
+ """.format(
23
+ intro=INTRO_BLURB,
24
+ instruction_key=INSTRUCTION_KEY,
25
+ instruction="{instruction}",
26
+ response_key=RESPONSE_KEY,
27
+ )
28
+
29
+
30
+ def get_special_token_id(tokenizer: PreTrainedTokenizer, key: str) -> int:
31
+ """Gets the token ID for a given string that has been added to the tokenizer as a special token.
32
+
33
+ When training, we configure the tokenizer so that the sequences like "### Instruction:" and "### End" are
34
+ treated specially and converted to a single, new token. This retrieves the token ID each of these keys map to.
35
+
36
+ Args:
37
+ tokenizer (PreTrainedTokenizer): the tokenizer
38
+ key (str): the key to convert to a single token
39
+
40
+ Raises:
41
+ RuntimeError: if more than one ID was generated
42
+
43
+ Returns:
44
+ int: the token ID for the given key
45
+ """
46
+ token_ids = tokenizer.encode(key)
47
+ if len(token_ids) > 1:
48
+ raise ValueError(f"Expected only a single token for '{key}' but found {token_ids}")
49
+ return token_ids[0]
50
+
51
+
52
+ class InstructionTextGenerationPipeline(Pipeline):
53
+ def __init__(
54
+ self, *args, do_sample: bool = True, max_new_tokens: int = 256, top_p: float = 0.92, top_k: int = 0, **kwargs
55
+ ):
56
+ super().__init__(*args, do_sample=do_sample, max_new_tokens=max_new_tokens, top_p=top_p, top_k=top_k, **kwargs)
57
+
58
+ def _sanitize_parameters(self, return_instruction_text=False, **generate_kwargs):
59
+ preprocess_params = {}
60
+
61
+ # newer versions of the tokenizer configure the response key as a special token. newer versions still may
62
+ # append a newline to yield a single token. find whatever token is configured for the response key.
63
+ tokenizer_response_key = next(
64
+ (token for token in self.tokenizer.additional_special_tokens if token.startswith(RESPONSE_KEY)), None
65
+ )
66
+
67
+ response_key_token_id = None
68
+ end_key_token_id = None
69
+ if tokenizer_response_key:
70
+ try:
71
+ response_key_token_id = get_special_token_id(self.tokenizer, tokenizer_response_key)
72
+ end_key_token_id = get_special_token_id(self.tokenizer, END_KEY)
73
+
74
+ # Ensure generation stops once it generates "### End"
75
+ generate_kwargs["eos_token_id"] = end_key_token_id
76
+ except ValueError:
77
+ pass
78
+
79
+ forward_params = generate_kwargs
80
+ postprocess_params = {
81
+ "response_key_token_id": response_key_token_id,
82
+ "end_key_token_id": end_key_token_id,
83
+ "return_instruction_text": return_instruction_text,
84
+ }
85
+
86
+ return preprocess_params, forward_params, postprocess_params
87
+
88
+ def preprocess(self, instruction_text, **generate_kwargs):
89
+ prompt_text = PROMPT_FOR_GENERATION_FORMAT.format(instruction=instruction_text)
90
+ inputs = self.tokenizer(
91
+ prompt_text,
92
+ return_tensors="pt",
93
+ )
94
+ inputs["prompt_text"] = prompt_text
95
+ inputs["instruction_text"] = instruction_text
96
+ return inputs
97
+
98
+ def _forward(self, model_inputs, **generate_kwargs):
99
+ input_ids = model_inputs["input_ids"]
100
+ attention_mask = model_inputs.get("attention_mask", None)
101
+ generated_sequence = self.model.generate(
102
+ input_ids=input_ids.to(self.model.device),
103
+ attention_mask=attention_mask,
104
+ pad_token_id=self.tokenizer.pad_token_id,
105
+ **generate_kwargs,
106
+ )[0].cpu()
107
+ instruction_text = model_inputs.pop("instruction_text")
108
+ return {"generated_sequence": generated_sequence, "input_ids": input_ids, "instruction_text": instruction_text}
109
+
110
+ def postprocess(self, model_outputs, response_key_token_id, end_key_token_id, return_instruction_text):
111
+ sequence = model_outputs["generated_sequence"]
112
+ instruction_text = model_outputs["instruction_text"]
113
+
114
+ # The response will be set to this variable if we can identify it.
115
+ decoded = None
116
+
117
+ # If we have token IDs for the response and end, then we can find the tokens and only decode between them.
118
+ if response_key_token_id and end_key_token_id:
119
+ # Find where "### Response:" is first found in the generated tokens. Considering this is part of the
120
+ # prompt, we should definitely find it. We will return the tokens found after this token.
121
+ response_pos = None
122
+ response_positions = np.where(sequence == response_key_token_id)[0]
123
+ if len(response_positions) == 0:
124
+ pass
125
+ else:
126
+ response_pos = response_positions[0]
127
+
128
+ if response_pos:
129
+ # Next find where "### End" is located. The model has been trained to end its responses with this
130
+ # sequence (or actually, the token ID it maps to, since it is a special token). We may not find
131
+ # this token, as the response could be truncated. If we don't find it then just return everything
132
+ # to the end. Note that even though we set eos_token_id, we still see the this token at the end.
133
+ end_pos = None
134
+ end_positions = np.where(sequence == end_key_token_id)[0]
135
+ if len(end_positions) > 0:
136
+ end_pos = end_positions[0]
137
+
138
+ decoded = self.tokenizer.decode(sequence[response_pos + 1 : end_pos]).strip()
139
+ else:
140
+ # Otherwise we'll decode everything and use a regex to find the response and end.
141
+
142
+ fully_decoded = self.tokenizer.decode(sequence)
143
+
144
+ # The response appears after "### Response:". The model has been trained to append "### End" at the
145
+ # end.
146
+ m = re.search(r"#+\s*Response:\s*(.+?)#+\s*End", fully_decoded, flags=re.DOTALL)
147
+
148
+ if m:
149
+ decoded = m.group(1).strip()
150
+ else:
151
+ # The model might not generate the "### End" sequence before reaching the max tokens. In this case,
152
+ # return everything after "### Response:".
153
+ m = re.search(r"#+\s*Response:\s*(.+)", fully_decoded, flags=re.DOTALL)
154
+ if m:
155
+ decoded = m.group(1).strip()
156
+
157
+ if return_instruction_text:
158
+ return {"instruction_text": instruction_text, "generated_text": decoded}
159
+
160
+ return decoded