Spaces:
Sleeping
Sleeping
Update ag4masses/alphageometry/lm_inference.py
Browse files- ag4masses/alphageometry/lm_inference.py +189 -189
ag4masses/alphageometry/lm_inference.py
CHANGED
@@ -1,189 +1,189 @@
|
|
1 |
-
# Copyright 2023 DeepMind Technologies Limited
|
2 |
-
#
|
3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
-
# you may not use this file except in compliance with the License.
|
5 |
-
# You may obtain a copy of the License at
|
6 |
-
#
|
7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
-
#
|
9 |
-
# Unless required by applicable law or agreed to in writing, software
|
10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
-
# See the License for the specific language governing permissions and
|
13 |
-
# limitations under the License.
|
14 |
-
# ==============================================================================
|
15 |
-
|
16 |
-
"""Wrapper for language modeling inference implemented in Meliad."""
|
17 |
-
from typing import Any, Dict
|
18 |
-
|
19 |
-
import jax
|
20 |
-
import models # pylint: disable=unused-import
|
21 |
-
import t5.data
|
22 |
-
from
|
23 |
-
|
24 |
-
|
25 |
-
np = jax.numpy
|
26 |
-
|
27 |
-
|
28 |
-
Trainer = inference_utils.Trainer
|
29 |
-
|
30 |
-
MetricsOutput = Dict[str, Any] # Metrics output by model.
|
31 |
-
|
32 |
-
|
33 |
-
parse_gin_configuration = inference_utils.parse_gin_configuration
|
34 |
-
|
35 |
-
|
36 |
-
class LanguageModelInference:
|
37 |
-
"""Meliad wrapper for LM inference."""
|
38 |
-
|
39 |
-
def __init__(self, vocab_path: str, load_dir: str, mode='beam_search'):
|
40 |
-
self.vocab = t5.data.SentencePieceVocabulary(vocab_path)
|
41 |
-
|
42 |
-
# This task won't be pulling from a dataset.
|
43 |
-
def null_iter_fn() -> None:
|
44 |
-
return None
|
45 |
-
|
46 |
-
process_summaries_f = inference_utils.models.process_summaries_function(
|
47 |
-
self.vocab
|
48 |
-
)
|
49 |
-
|
50 |
-
trainer = inference_utils.training_loop.Trainer(
|
51 |
-
get_training_dataset_iterator=null_iter_fn,
|
52 |
-
get_test_dataset_iterator=None,
|
53 |
-
pretty_print_input_function=None,
|
54 |
-
process_summaries_function=process_summaries_f,
|
55 |
-
load_dir=load_dir,
|
56 |
-
workdir='', # Don't log or save checkpoints.
|
57 |
-
replicate_mode=False,
|
58 |
-
) # Run on a single device at batch size 1.
|
59 |
-
self.trainer = trainer
|
60 |
-
|
61 |
-
# Create and initialize the model.
|
62 |
-
(tstate, _, imodel, prngs) = trainer.initialize_model()
|
63 |
-
self.imodel = imodel
|
64 |
-
self.batch_size = imodel.task_config.batch_size
|
65 |
-
|
66 |
-
self.n = imodel.num_heads
|
67 |
-
self.h = imodel.head_size
|
68 |
-
|
69 |
-
# Create an inference task.
|
70 |
-
writers = {}
|
71 |
-
self.task = trainer.create_training_task(mode, imodel, prngs, writers) # pylint: disable=too-many-function-args
|
72 |
-
|
73 |
-
# Register any additional actions.
|
74 |
-
# Actions are cleared first for use with colab.
|
75 |
-
inference_utils.training_loop.clear_interstep_callbacks()
|
76 |
-
inference_utils.training_loop.register_interstep_callbacks()
|
77 |
-
self.tstate = tstate
|
78 |
-
|
79 |
-
# some default parameters.
|
80 |
-
eos = [0] * 1024
|
81 |
-
for idx in self.encode_list(['.', ';']):
|
82 |
-
eos[idx] = 1
|
83 |
-
|
84 |
-
self.eos = np.array(eos, dtype=np.bfloat16)
|
85 |
-
self.mask = jax.numpy.ones([1024], dtype=np.bfloat16)
|
86 |
-
|
87 |
-
def decode(self, ids: list[int]) -> str:
|
88 |
-
return self.vocab.decode(ids)
|
89 |
-
|
90 |
-
def decode_list(self, tokens: list[int]) -> list[str]:
|
91 |
-
return [self.decode([tok]) for tok in tokens]
|
92 |
-
|
93 |
-
def encode(self, inputs_str: str) -> list[int]:
|
94 |
-
return self.vocab.encode(inputs_str)
|
95 |
-
|
96 |
-
def encode_list(self, inputs_strs: list[str]) -> list[int]:
|
97 |
-
result = [self.vocab.encode(x) for x in inputs_strs]
|
98 |
-
assert all([len(x) == 1 for x in result]), [
|
99 |
-
self.decode(x) for x in result if len(x) != 1
|
100 |
-
]
|
101 |
-
return [x[0] for x in result]
|
102 |
-
|
103 |
-
def call(
|
104 |
-
self,
|
105 |
-
inputs: np.ndarray,
|
106 |
-
dstate: tuple[dict[str, np.ndarray], ...] = None,
|
107 |
-
eos: np.ndarray = None,
|
108 |
-
mask: np.ndarray = None,
|
109 |
-
) -> MetricsOutput:
|
110 |
-
"""Call the meliad model."""
|
111 |
-
batch_size, length = inputs.shape
|
112 |
-
inputs = jax.numpy.pad(inputs, [(0, 0), (0, 1024 - length)])
|
113 |
-
|
114 |
-
if eos is None:
|
115 |
-
eos = self.eos
|
116 |
-
if mask is None:
|
117 |
-
mask = self.mask
|
118 |
-
|
119 |
-
x = {'targets': inputs, 'length': length, 'eos': eos, 'mask': mask}
|
120 |
-
|
121 |
-
if dstate is not None:
|
122 |
-
x['start_of_sequence'] = jax.numpy.array([False] * batch_size)
|
123 |
-
else:
|
124 |
-
dstate = tuple(
|
125 |
-
[{ # this dummy value will never be used.
|
126 |
-
'current_index': np.array([0] * batch_size, dtype=np.int32),
|
127 |
-
'keys': np.zeros(
|
128 |
-
(batch_size, 2048, self.n, self.h), dtype=np.bfloat16
|
129 |
-
),
|
130 |
-
'values': np.zeros(
|
131 |
-
(batch_size, 2048, self.n, self.h), dtype=np.bfloat16
|
132 |
-
),
|
133 |
-
'recurrent_kvq': None,
|
134 |
-
'relative_position_bias': np.zeros(
|
135 |
-
(batch_size, self.n, 1, 1024), dtype=np.bfloat16
|
136 |
-
),
|
137 |
-
}]
|
138 |
-
* 12
|
139 |
-
)
|
140 |
-
x['start_of_sequence'] = jax.numpy.array([True] * batch_size)
|
141 |
-
|
142 |
-
x['dstate'] = dstate
|
143 |
-
_, metrics_np = self.task.run_step(self.tstate, x, 0)
|
144 |
-
return metrics_np
|
145 |
-
|
146 |
-
def beam_decode(
|
147 |
-
self,
|
148 |
-
inputs: str,
|
149 |
-
eos_tokens: np.ndarray = None,
|
150 |
-
mask_tokens: np.ndarray = None,
|
151 |
-
dstate: dict[str, np.ndarray] = None,
|
152 |
-
) -> MetricsOutput:
|
153 |
-
"""Beam search."""
|
154 |
-
inputs = jax.numpy.array([self.vocab.encode(inputs)] * self.batch_size)
|
155 |
-
|
156 |
-
eos = self.eos
|
157 |
-
if eos_tokens is not None:
|
158 |
-
eos_ids = self.encode_list(eos_tokens)
|
159 |
-
eos = np.array(
|
160 |
-
[1 if idx in eos_ids else 0 for idx in range(1024)], dtype=np.bfloat16
|
161 |
-
).reshape((1, 1, 1024))
|
162 |
-
|
163 |
-
mask = self.mask
|
164 |
-
if mask_tokens is not None:
|
165 |
-
mask_ids = self.encode_list(mask_tokens)
|
166 |
-
mask = np.array(
|
167 |
-
[0 if idx in mask_ids else 1 for idx in range(1024)],
|
168 |
-
dtype=np.bfloat16,
|
169 |
-
).reshape((1, 1, 1024))
|
170 |
-
|
171 |
-
metrics_np = self.call(inputs, dstate=dstate, eos=eos, mask=mask)
|
172 |
-
|
173 |
-
finished_seqs = metrics_np['finished_seqs']
|
174 |
-
finished_scores = metrics_np['finished_scores']
|
175 |
-
|
176 |
-
seqs = []
|
177 |
-
scores = []
|
178 |
-
for seq, score in zip(finished_seqs, finished_scores):
|
179 |
-
seq = self.decode(seq[1:])
|
180 |
-
seqs.append(seq)
|
181 |
-
scores.append(score)
|
182 |
-
|
183 |
-
return {
|
184 |
-
'finished_seqs': finished_seqs,
|
185 |
-
'finished_scores': finished_scores,
|
186 |
-
'seqs_str': seqs,
|
187 |
-
'scores': scores,
|
188 |
-
'dstate': metrics_np['dstate'],
|
189 |
-
}
|
|
|
1 |
+
# Copyright 2023 DeepMind Technologies Limited
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
# ==============================================================================
|
15 |
+
|
16 |
+
"""Wrapper for language modeling inference implemented in Meliad."""
|
17 |
+
from typing import Any, Dict
|
18 |
+
|
19 |
+
import jax
|
20 |
+
import models # pylint: disable=unused-import
|
21 |
+
import t5.data
|
22 |
+
from aglib.meliad.transformer import inference_utils
|
23 |
+
|
24 |
+
|
25 |
+
np = jax.numpy
|
26 |
+
|
27 |
+
|
28 |
+
Trainer = inference_utils.Trainer
|
29 |
+
|
30 |
+
MetricsOutput = Dict[str, Any] # Metrics output by model.
|
31 |
+
|
32 |
+
|
33 |
+
parse_gin_configuration = inference_utils.parse_gin_configuration
|
34 |
+
|
35 |
+
|
36 |
+
class LanguageModelInference:
|
37 |
+
"""Meliad wrapper for LM inference."""
|
38 |
+
|
39 |
+
def __init__(self, vocab_path: str, load_dir: str, mode='beam_search'):
|
40 |
+
self.vocab = t5.data.SentencePieceVocabulary(vocab_path)
|
41 |
+
|
42 |
+
# This task won't be pulling from a dataset.
|
43 |
+
def null_iter_fn() -> None:
|
44 |
+
return None
|
45 |
+
|
46 |
+
process_summaries_f = inference_utils.models.process_summaries_function(
|
47 |
+
self.vocab
|
48 |
+
)
|
49 |
+
|
50 |
+
trainer = inference_utils.training_loop.Trainer(
|
51 |
+
get_training_dataset_iterator=null_iter_fn,
|
52 |
+
get_test_dataset_iterator=None,
|
53 |
+
pretty_print_input_function=None,
|
54 |
+
process_summaries_function=process_summaries_f,
|
55 |
+
load_dir=load_dir,
|
56 |
+
workdir='', # Don't log or save checkpoints.
|
57 |
+
replicate_mode=False,
|
58 |
+
) # Run on a single device at batch size 1.
|
59 |
+
self.trainer = trainer
|
60 |
+
|
61 |
+
# Create and initialize the model.
|
62 |
+
(tstate, _, imodel, prngs) = trainer.initialize_model()
|
63 |
+
self.imodel = imodel
|
64 |
+
self.batch_size = imodel.task_config.batch_size
|
65 |
+
|
66 |
+
self.n = imodel.num_heads
|
67 |
+
self.h = imodel.head_size
|
68 |
+
|
69 |
+
# Create an inference task.
|
70 |
+
writers = {}
|
71 |
+
self.task = trainer.create_training_task(mode, imodel, prngs, writers) # pylint: disable=too-many-function-args
|
72 |
+
|
73 |
+
# Register any additional actions.
|
74 |
+
# Actions are cleared first for use with colab.
|
75 |
+
inference_utils.training_loop.clear_interstep_callbacks()
|
76 |
+
inference_utils.training_loop.register_interstep_callbacks()
|
77 |
+
self.tstate = tstate
|
78 |
+
|
79 |
+
# some default parameters.
|
80 |
+
eos = [0] * 1024
|
81 |
+
for idx in self.encode_list(['.', ';']):
|
82 |
+
eos[idx] = 1
|
83 |
+
|
84 |
+
self.eos = np.array(eos, dtype=np.bfloat16)
|
85 |
+
self.mask = jax.numpy.ones([1024], dtype=np.bfloat16)
|
86 |
+
|
87 |
+
def decode(self, ids: list[int]) -> str:
|
88 |
+
return self.vocab.decode(ids)
|
89 |
+
|
90 |
+
def decode_list(self, tokens: list[int]) -> list[str]:
|
91 |
+
return [self.decode([tok]) for tok in tokens]
|
92 |
+
|
93 |
+
def encode(self, inputs_str: str) -> list[int]:
|
94 |
+
return self.vocab.encode(inputs_str)
|
95 |
+
|
96 |
+
def encode_list(self, inputs_strs: list[str]) -> list[int]:
|
97 |
+
result = [self.vocab.encode(x) for x in inputs_strs]
|
98 |
+
assert all([len(x) == 1 for x in result]), [
|
99 |
+
self.decode(x) for x in result if len(x) != 1
|
100 |
+
]
|
101 |
+
return [x[0] for x in result]
|
102 |
+
|
103 |
+
def call(
|
104 |
+
self,
|
105 |
+
inputs: np.ndarray,
|
106 |
+
dstate: tuple[dict[str, np.ndarray], ...] = None,
|
107 |
+
eos: np.ndarray = None,
|
108 |
+
mask: np.ndarray = None,
|
109 |
+
) -> MetricsOutput:
|
110 |
+
"""Call the meliad model."""
|
111 |
+
batch_size, length = inputs.shape
|
112 |
+
inputs = jax.numpy.pad(inputs, [(0, 0), (0, 1024 - length)])
|
113 |
+
|
114 |
+
if eos is None:
|
115 |
+
eos = self.eos
|
116 |
+
if mask is None:
|
117 |
+
mask = self.mask
|
118 |
+
|
119 |
+
x = {'targets': inputs, 'length': length, 'eos': eos, 'mask': mask}
|
120 |
+
|
121 |
+
if dstate is not None:
|
122 |
+
x['start_of_sequence'] = jax.numpy.array([False] * batch_size)
|
123 |
+
else:
|
124 |
+
dstate = tuple(
|
125 |
+
[{ # this dummy value will never be used.
|
126 |
+
'current_index': np.array([0] * batch_size, dtype=np.int32),
|
127 |
+
'keys': np.zeros(
|
128 |
+
(batch_size, 2048, self.n, self.h), dtype=np.bfloat16
|
129 |
+
),
|
130 |
+
'values': np.zeros(
|
131 |
+
(batch_size, 2048, self.n, self.h), dtype=np.bfloat16
|
132 |
+
),
|
133 |
+
'recurrent_kvq': None,
|
134 |
+
'relative_position_bias': np.zeros(
|
135 |
+
(batch_size, self.n, 1, 1024), dtype=np.bfloat16
|
136 |
+
),
|
137 |
+
}]
|
138 |
+
* 12
|
139 |
+
)
|
140 |
+
x['start_of_sequence'] = jax.numpy.array([True] * batch_size)
|
141 |
+
|
142 |
+
x['dstate'] = dstate
|
143 |
+
_, metrics_np = self.task.run_step(self.tstate, x, 0)
|
144 |
+
return metrics_np
|
145 |
+
|
146 |
+
def beam_decode(
|
147 |
+
self,
|
148 |
+
inputs: str,
|
149 |
+
eos_tokens: np.ndarray = None,
|
150 |
+
mask_tokens: np.ndarray = None,
|
151 |
+
dstate: dict[str, np.ndarray] = None,
|
152 |
+
) -> MetricsOutput:
|
153 |
+
"""Beam search."""
|
154 |
+
inputs = jax.numpy.array([self.vocab.encode(inputs)] * self.batch_size)
|
155 |
+
|
156 |
+
eos = self.eos
|
157 |
+
if eos_tokens is not None:
|
158 |
+
eos_ids = self.encode_list(eos_tokens)
|
159 |
+
eos = np.array(
|
160 |
+
[1 if idx in eos_ids else 0 for idx in range(1024)], dtype=np.bfloat16
|
161 |
+
).reshape((1, 1, 1024))
|
162 |
+
|
163 |
+
mask = self.mask
|
164 |
+
if mask_tokens is not None:
|
165 |
+
mask_ids = self.encode_list(mask_tokens)
|
166 |
+
mask = np.array(
|
167 |
+
[0 if idx in mask_ids else 1 for idx in range(1024)],
|
168 |
+
dtype=np.bfloat16,
|
169 |
+
).reshape((1, 1, 1024))
|
170 |
+
|
171 |
+
metrics_np = self.call(inputs, dstate=dstate, eos=eos, mask=mask)
|
172 |
+
|
173 |
+
finished_seqs = metrics_np['finished_seqs']
|
174 |
+
finished_scores = metrics_np['finished_scores']
|
175 |
+
|
176 |
+
seqs = []
|
177 |
+
scores = []
|
178 |
+
for seq, score in zip(finished_seqs, finished_scores):
|
179 |
+
seq = self.decode(seq[1:])
|
180 |
+
seqs.append(seq)
|
181 |
+
scores.append(score)
|
182 |
+
|
183 |
+
return {
|
184 |
+
'finished_seqs': finished_seqs,
|
185 |
+
'finished_scores': finished_scores,
|
186 |
+
'seqs_str': seqs,
|
187 |
+
'scores': scores,
|
188 |
+
'dstate': metrics_np['dstate'],
|
189 |
+
}
|