RamAnanth1 commited on
Commit
189eb29
1 Parent(s): f631cd0

Create instruct_pipeline.py

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