Added app and model
Browse files- concept--main/GP.py +387 -0
- concept--main/Nods.py +97 -0
- concept--main/Vit_concept.py +153 -0
- concept--main/app.py +82 -0
- concept--main/custom_t5_vit.py +1833 -0
- concept--main/dsl.py +542 -0
- concept--main/fittnes.py +15 -0
- concept--main/interface.py +61 -0
- concept--main/model/final_cls_model +1 -0
- concept--main/model/final_cls_modell.pt +3 -0
- concept--main/requirements.txt +9 -0
- concept--main/task_loader.py +33 -0
- concept--main/tokenizer_vs22_extendarctokens/special_tokens_map.json +9 -0
- concept--main/tokenizer_vs22_extendarctokens/tokenizer.json +241 -0
- concept--main/tokenizer_vs22_extendarctokens/tokenizer_config.json +192 -0
- concept--main/tokenizer_vs22_extendarctokens/tt +1 -0
- concept--main/utils.py +135 -0
- concept--main/visualization.py +82 -0
- extr.py +1 -0
concept--main/GP.py
ADDED
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
class GPContext:
|
5 |
+
def __init__(self, grid):
|
6 |
+
self.grid = deepcopy(grid)
|
7 |
+
self.objects = []
|
8 |
+
self.top_object = None
|
9 |
+
self.shift = None
|
10 |
+
|
11 |
+
|
12 |
+
def extract_object(grid):
|
13 |
+
ctx = GPContext(grid)
|
14 |
+
rows, cols = len(ctx.grid), len(ctx.grid[0])
|
15 |
+
visited = [[False]*cols for _ in range(rows)]
|
16 |
+
|
17 |
+
def bfs(r, c, val):
|
18 |
+
queue = deque([(r, c)])
|
19 |
+
block = []
|
20 |
+
visited[r][c] = True
|
21 |
+
while queue:
|
22 |
+
x, y = queue.popleft()
|
23 |
+
block.append((x, y))
|
24 |
+
for dx, dy in [(-1,0), (1,0), (0,-1), (0,1)]:
|
25 |
+
nx, ny = x + dx, y + dy
|
26 |
+
if 0 <= nx < rows and 0 <= ny < cols and not visited[nx][ny] and ctx.grid[nx][ny] == val:
|
27 |
+
visited[nx][ny] = True
|
28 |
+
queue.append((nx, ny))
|
29 |
+
return block
|
30 |
+
|
31 |
+
for r in range(rows):
|
32 |
+
for c in range(cols):
|
33 |
+
if ctx.grid[r][c] != 0 and not visited[r][c]:
|
34 |
+
block = bfs(r, c, ctx.grid[r][c])
|
35 |
+
top_row = min(x for x, y in block)
|
36 |
+
value = ctx.grid[block[0][0]][block[0][1]]
|
37 |
+
ctx.objects.append((top_row, value, block))
|
38 |
+
|
39 |
+
return ctx
|
40 |
+
|
41 |
+
def sort_objects_by_column(ctx):
|
42 |
+
ctx.objects.sort(key=lambda obj: min(y for x, y in obj[2]))
|
43 |
+
return ctx
|
44 |
+
|
45 |
+
def sort_object(ctx):
|
46 |
+
ctx.objects.sort(key=lambda obj: obj[0])
|
47 |
+
return ctx
|
48 |
+
def move_right_most_object(ctx):
|
49 |
+
if not ctx.objects:
|
50 |
+
return ctx.grid
|
51 |
+
|
52 |
+
# Get rightmost object: object with largest column index
|
53 |
+
rightmost_object = max(ctx.objects, key=lambda obj: max(y for x, y in obj[2]))
|
54 |
+
_, value, block = rightmost_object
|
55 |
+
|
56 |
+
for x, y in block:
|
57 |
+
ctx.grid[x][y] = 0
|
58 |
+
|
59 |
+
shift = 0
|
60 |
+
cols = len(ctx.grid[0])
|
61 |
+
while True:
|
62 |
+
can_move = True
|
63 |
+
for x, y in block:
|
64 |
+
new_y = y + shift + 1
|
65 |
+
if new_y >= cols or ctx.grid[x][new_y] != 0:
|
66 |
+
can_move = False
|
67 |
+
break
|
68 |
+
if not can_move:
|
69 |
+
break
|
70 |
+
shift += 1
|
71 |
+
|
72 |
+
for x, y in block:
|
73 |
+
ctx.grid[x][y + shift] = value
|
74 |
+
|
75 |
+
return ctx.grid
|
76 |
+
def move_left_most_object(ctx):
|
77 |
+
if not ctx.objects:
|
78 |
+
return ctx.grid
|
79 |
+
|
80 |
+
# Get leftmost object: object with smallest column index
|
81 |
+
leftmost_object = min(ctx.objects, key=lambda obj: min(y for x, y in obj[2]))
|
82 |
+
_, value, block = leftmost_object
|
83 |
+
|
84 |
+
for x, y in block:
|
85 |
+
ctx.grid[x][y] = 0
|
86 |
+
|
87 |
+
shift = 0
|
88 |
+
while True:
|
89 |
+
can_move = True
|
90 |
+
for x, y in block:
|
91 |
+
new_y = y - (shift + 1)
|
92 |
+
if new_y < 0 or ctx.grid[x][new_y] != 0:
|
93 |
+
can_move = False
|
94 |
+
break
|
95 |
+
if not can_move:
|
96 |
+
break
|
97 |
+
shift += 1
|
98 |
+
|
99 |
+
for x, y in block:
|
100 |
+
ctx.grid[x][y - shift] = value
|
101 |
+
|
102 |
+
return ctx.grid
|
103 |
+
|
104 |
+
def move_bottom_most_object(ctx):
|
105 |
+
if not ctx.objects:
|
106 |
+
return ctx.grid
|
107 |
+
|
108 |
+
# Get bottommost object (last one in the list after sorting by top_row)
|
109 |
+
bottom_object = ctx.objects[-1]
|
110 |
+
_, value, block = bottom_object
|
111 |
+
|
112 |
+
# Remove it from the grid
|
113 |
+
for x, y in block:
|
114 |
+
ctx.grid[x][y] = 0
|
115 |
+
|
116 |
+
# Compute shift (same as top, move down)
|
117 |
+
shift = 0
|
118 |
+
rows = len(ctx.grid)
|
119 |
+
while True:
|
120 |
+
can_move = True
|
121 |
+
for x, y in block:
|
122 |
+
new_x = x + shift + 1
|
123 |
+
if new_x >= rows or ctx.grid[new_x][y] != 0:
|
124 |
+
can_move = False
|
125 |
+
break
|
126 |
+
if not can_move:
|
127 |
+
break
|
128 |
+
shift += 1
|
129 |
+
|
130 |
+
# Place object
|
131 |
+
for x, y in block:
|
132 |
+
ctx.grid[x + shift][y] = value
|
133 |
+
|
134 |
+
return ctx.grid
|
135 |
+
|
136 |
+
def move_top_most_object(ctx):
|
137 |
+
if not ctx.objects:
|
138 |
+
return ctx.grid
|
139 |
+
|
140 |
+
# Get topmost object
|
141 |
+
top_object = ctx.objects[0]
|
142 |
+
_, value, block = top_object
|
143 |
+
|
144 |
+
# Remove it from the grid
|
145 |
+
for x, y in block:
|
146 |
+
ctx.grid[x][y] = 0
|
147 |
+
|
148 |
+
# Compute shift
|
149 |
+
shift = 0
|
150 |
+
rows = len(ctx.grid)
|
151 |
+
while True:
|
152 |
+
can_move = True
|
153 |
+
for x, y in block:
|
154 |
+
new_x = x + shift + 1
|
155 |
+
if new_x >= rows or ctx.grid[new_x][y] != 0:
|
156 |
+
can_move = False
|
157 |
+
break
|
158 |
+
if not can_move:
|
159 |
+
break
|
160 |
+
shift += 1
|
161 |
+
|
162 |
+
# Place object
|
163 |
+
for x, y in block:
|
164 |
+
ctx.grid[x + shift][y] = value
|
165 |
+
|
166 |
+
return ctx.grid
|
167 |
+
def reverse_object_order(ctx):
|
168 |
+
ctx.reversed_objects = list(reversed(ctx.objects))
|
169 |
+
return ctx
|
170 |
+
|
171 |
+
# Step 3: Clear grid and place objects from top downward
|
172 |
+
def place_objects(ctx):
|
173 |
+
rows, cols = len(ctx.grid), len(ctx.grid[0])
|
174 |
+
new_grid = [[0]*cols for _ in range(rows)]
|
175 |
+
current_row = 0
|
176 |
+
|
177 |
+
for _, value, block in ctx.reversed_objects:
|
178 |
+
# Shift block so top of block aligns with current_row
|
179 |
+
min_row = min(x for x, y in block)
|
180 |
+
row_shift = current_row - min_row
|
181 |
+
|
182 |
+
# Compute height of block to update current_row
|
183 |
+
block_height = max(x for x, y in block) - min_row + 1
|
184 |
+
|
185 |
+
for x, y in block:
|
186 |
+
new_x = x + row_shift
|
187 |
+
if 0 <= new_x < rows:
|
188 |
+
new_grid[new_x][y] = value
|
189 |
+
|
190 |
+
current_row += block_height
|
191 |
+
|
192 |
+
return new_grid
|
193 |
+
from dsl import *
|
194 |
+
|
195 |
+
concept_hierarchy = {
|
196 |
+
"Above Below": {
|
197 |
+
"remove below horizontal": ["flip_horizontal", "flip_vertical"],
|
198 |
+
"Fill below the pattern": ["rotate_90", "rotate_180", "rotate_270"],
|
199 |
+
"Move object": ["extract_object", "sort_objects", "move_top_most_object","extract_object""move_bottom_most_object","move_left_most_object","move_right_most_object"],
|
200 |
+
"reverse object":[ "place_objects", "reverse_object_order","extract_object"]
|
201 |
+
},
|
202 |
+
"Clean Up": {
|
203 |
+
"Copy the grid content": ["find_center_pixel"]
|
204 |
+
}
|
205 |
+
}
|
206 |
+
|
207 |
+
primitive_function_registry = {
|
208 |
+
"move_top_most_object": move_top_most_object,
|
209 |
+
"move_bottom_most_object": move_bottom_most_object,
|
210 |
+
"move_right_most_object":move_right_most_object,
|
211 |
+
"move_left_most_object":move_left_most_object,
|
212 |
+
"extract_object": extract_object,
|
213 |
+
"sort_objects": sort_object,
|
214 |
+
"find_center_pixel":find_center_pixel,
|
215 |
+
"extract_object": extract_object,
|
216 |
+
"reverse_object_order": reverse_object_order,
|
217 |
+
"place_objects": place_objects
|
218 |
+
}
|
219 |
+
|
220 |
+
def get_sub_concepts_and_functions(high_level_concepts):
|
221 |
+
allowed_functions = []
|
222 |
+
for hlc in high_level_concepts:
|
223 |
+
sub_concepts = concept_hierarchy.get(hlc, {})
|
224 |
+
for slc_funcs in sub_concepts.values():
|
225 |
+
allowed_functions.extend(slc_funcs)
|
226 |
+
return list(set(allowed_functions))
|
227 |
+
import random
|
228 |
+
|
229 |
+
TERMINALS = ["input_grid"]
|
230 |
+
|
231 |
+
class Node:
|
232 |
+
def __init__(self, value, children=None):
|
233 |
+
self.value = value
|
234 |
+
self.children = children if children else []
|
235 |
+
|
236 |
+
def __str__(self):
|
237 |
+
if self.children:
|
238 |
+
return f"{self.value}({', '.join(str(child) for child in self.children)})"
|
239 |
+
return str(self.value)
|
240 |
+
|
241 |
+
def evaluate(self, input_grid):
|
242 |
+
if self.value == "input_grid":
|
243 |
+
return input_grid
|
244 |
+
child_values = [child.evaluate(input_grid) for child in self.children]
|
245 |
+
func = primitive_function_registry.get(self.value)
|
246 |
+
if func is None:
|
247 |
+
raise ValueError(f"Unknown function: {self.value}")
|
248 |
+
return func(*child_values)
|
249 |
+
|
250 |
+
|
251 |
+
def generate_random_program(max_depth, current_depth=0, allowed_functions=None):
|
252 |
+
if current_depth >= max_depth or (current_depth > 0 and random.random() < 0.2):
|
253 |
+
return Node(random.choice(TERMINALS))
|
254 |
+
else:
|
255 |
+
func_name = random.choice(allowed_functions) if allowed_functions else random.choice(list(primitive_function_registry.keys()))
|
256 |
+
children = [generate_random_program(max_depth, current_depth+1, allowed_functions) for _ in range(1)] # assuming arity=1
|
257 |
+
return Node(func_name, children)
|
258 |
+
|
259 |
+
|
260 |
+
def get_all_nodes(program):
|
261 |
+
nodes = [program]
|
262 |
+
for child in program.children:
|
263 |
+
nodes.extend(get_all_nodes(child))
|
264 |
+
return nodes
|
265 |
+
|
266 |
+
|
267 |
+
def crossover(parent1, parent2):
|
268 |
+
import copy
|
269 |
+
child1, child2 = copy.deepcopy(parent1), copy.deepcopy(parent2)
|
270 |
+
nodes1, nodes2 = get_all_nodes(child1), get_all_nodes(child2)
|
271 |
+
point1, point2 = random.choice(nodes1), random.choice(nodes2)
|
272 |
+
point1.value, point1.children, point2.value, point2.children = point2.value, point2.children, point1.value, point1.children
|
273 |
+
return child1, child2
|
274 |
+
|
275 |
+
|
276 |
+
def mutation(program, max_depth, mutation_rate, allowed_functions):
|
277 |
+
import copy
|
278 |
+
mutant = copy.deepcopy(program)
|
279 |
+
nodes = get_all_nodes(mutant)
|
280 |
+
for node in nodes:
|
281 |
+
if random.random() < mutation_rate:
|
282 |
+
new_subtree = generate_random_program(max_depth=max_depth, current_depth=0, allowed_functions=allowed_functions)
|
283 |
+
node.value = new_subtree.value
|
284 |
+
node.children = new_subtree.children
|
285 |
+
return mutant
|
286 |
+
|
287 |
+
|
288 |
+
def tournament_selection(population, fitness_scores, k):
|
289 |
+
selected = []
|
290 |
+
for _ in range(len(population)):
|
291 |
+
participants = random.sample(list(zip(population, fitness_scores)), k)
|
292 |
+
winner = max(participants, key=lambda x: x[1])[0]
|
293 |
+
selected.append(winner)
|
294 |
+
return selected
|
295 |
+
|
296 |
+
|
297 |
+
class Generation:
|
298 |
+
def __init__(self, best_fitness, population):
|
299 |
+
self.best_fitness = best_fitness
|
300 |
+
self.population = population
|
301 |
+
|
302 |
+
def to_dict(self):
|
303 |
+
return {
|
304 |
+
"best_fitness": self.best_fitness,
|
305 |
+
"population": [str(ind) for ind in self.population]
|
306 |
+
}
|
307 |
+
|
308 |
+
def evaluate_fitness(program, input_output_pairs):
|
309 |
+
score = 0
|
310 |
+
for inp, expected in input_output_pairs:
|
311 |
+
try:
|
312 |
+
result = program.evaluate(inp)
|
313 |
+
if result == expected:
|
314 |
+
score += 1
|
315 |
+
except:
|
316 |
+
continue
|
317 |
+
return score
|
318 |
+
|
319 |
+
|
320 |
+
def genetic_programming(input_output_pairs, population_size, generations, mutation_rate, crossover_rate, max_depth, predicted_HLCs):
|
321 |
+
allowed_functions = get_sub_concepts_and_functions(predicted_HLCs)
|
322 |
+
population = [generate_random_program(max_depth, allowed_functions=allowed_functions) for _ in range(population_size)]
|
323 |
+
all_generations = []
|
324 |
+
best_program = None
|
325 |
+
|
326 |
+
for gen in range(generations):
|
327 |
+
fitness_scores = [evaluate_fitness(p, input_output_pairs) for p in population]
|
328 |
+
best_fitness = max(fitness_scores)
|
329 |
+
best_program = population[fitness_scores.index(best_fitness)]
|
330 |
+
|
331 |
+
selected = tournament_selection(population, fitness_scores, k=3)
|
332 |
+
next_generation = []
|
333 |
+
|
334 |
+
while len(next_generation) < population_size:
|
335 |
+
if random.random() < crossover_rate and len(selected) >= 2:
|
336 |
+
p1, p2 = random.sample(selected, 2)
|
337 |
+
c1, c2 = crossover(p1, p2)
|
338 |
+
next_generation.extend([c1, c2])
|
339 |
+
else:
|
340 |
+
parent = random.choice(selected)
|
341 |
+
child = mutation(parent, max_depth, mutation_rate, allowed_functions)
|
342 |
+
next_generation.append(child)
|
343 |
+
|
344 |
+
population = next_generation[:population_size]
|
345 |
+
all_generations.append(Generation(best_fitness, population))
|
346 |
+
print(f"Generation {gen} - Best Fitness: {best_fitness}")
|
347 |
+
|
348 |
+
return best_program, all_generations
|
349 |
+
|
350 |
+
if __name__ == "__main__":
|
351 |
+
if __name__ == "__main__":
|
352 |
+
input_output_pairs = [
|
353 |
+
(
|
354 |
+
[[0,0,0,0,0,0,0,0],
|
355 |
+
[0,3,3,3,0,0,0,0],
|
356 |
+
[0,0,0,0,0,0,0,0],
|
357 |
+
[0,4,4,4,0,0,0,0],
|
358 |
+
[0,4,4,4,0,0,0,0],
|
359 |
+
[0,4,4,4,0,0,0,0],
|
360 |
+
[0,0,0,0,0,3,3,3],
|
361 |
+
[0,0,3,3,3,0,0,0]],
|
362 |
+
|
363 |
+
[[0,0,0,0,0,0,0,0],
|
364 |
+
[0,0,0,0,0,0,0,0],
|
365 |
+
[0,3,3,3,0,0,0,0],
|
366 |
+
[0,4,4,4,0,0,0,0],
|
367 |
+
[0,4,4,4,0,0,0,0],
|
368 |
+
[0,4,4,4,0,0,0,0],
|
369 |
+
[0,0,0,0,0,3,3,3],
|
370 |
+
[0,0,3,3,3,0,0,0]]
|
371 |
+
)
|
372 |
+
]
|
373 |
+
|
374 |
+
|
375 |
+
predicted_HLCs = ["Above Beloww"]
|
376 |
+
|
377 |
+
|
378 |
+
best_program, generations = genetic_programming(
|
379 |
+
input_output_pairs=input_output_pairs,
|
380 |
+
population_size=500,
|
381 |
+
generations=700,
|
382 |
+
mutation_rate=0.2,
|
383 |
+
crossover_rate=0.7,
|
384 |
+
max_depth=3,
|
385 |
+
predicted_HLCs=predicted_HLCs
|
386 |
+
)
|
387 |
+
print("\nBest Program:", best_program)
|
concept--main/Nods.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
from dsl import *
|
3 |
+
# Dictionary of DSLs or primitive functions and terminals
|
4 |
+
|
5 |
+
import random
|
6 |
+
|
7 |
+
# Dictionary of DSLs or primitive functions and terminals
|
8 |
+
FUNCTIONS_dictionary = {
|
9 |
+
|
10 |
+
'reverse_object_top_bottom':(reverse_object_top_bottom,1),
|
11 |
+
'flip_horizontal': (flip_horizontal, 1),
|
12 |
+
'flip_vertical': (flip_vertical, 1),
|
13 |
+
'rotate_90': (rotate_90, 1),
|
14 |
+
'rotate_180': (rotate_180, 1),
|
15 |
+
'rotate_270': (rotate_270, 1),
|
16 |
+
'identity': (identity, 1),
|
17 |
+
'transform_blue_to_red': (transform_blue_to_red, 1),
|
18 |
+
'vertical_mirror': (vmirrors, 1),
|
19 |
+
'horizontal_mirror': (hmirror, 1),
|
20 |
+
'diagonal_mirror': (diamirror, 1),
|
21 |
+
'find_center_pixel':(find_center_pixel,1),
|
22 |
+
'get_object_bounds': (get_object_bounds,1),
|
23 |
+
'reverse_object_top_bottom':(reverse_object_top_bottom,1)
|
24 |
+
# Uncommented functions (if needed)
|
25 |
+
# 'extract_largest_row': (extract_largest_row, 1),
|
26 |
+
# 'extract_bottom_object': (extract_bottom_object, 1),
|
27 |
+
# 'extract_topmost_object': (extract_topmost_object, 1),
|
28 |
+
# 'fill_downward': (fill_downward, 1),
|
29 |
+
# 'keep_bottom_object': (keep_bottom_object, 1),
|
30 |
+
# 'remove_least_dominant_pixel': (remove_least_dominant_pixel, 1),
|
31 |
+
# 'remove_center_object': (remove_center_object, 1),
|
32 |
+
# 'remove_below_horizontal_line': (remove_below_horizontal_line, 1),
|
33 |
+
# 'swap_objects': (swap_objects, 1),
|
34 |
+
# 'draw_horizontal_vertical': (draw_horizontal_vertical, 1),
|
35 |
+
}
|
36 |
+
|
37 |
+
TERMINALS = [
|
38 |
+
('input_grid', lambda: None, 0)
|
39 |
+
]
|
40 |
+
|
41 |
+
class Node:
|
42 |
+
_id_counter = 0
|
43 |
+
|
44 |
+
def __init__(self, value, children=None):
|
45 |
+
self.id = Node._id_counter
|
46 |
+
Node._id_counter += 1
|
47 |
+
self.value = value
|
48 |
+
self.children = children if children is not None else []
|
49 |
+
|
50 |
+
def __str__(self):
|
51 |
+
if self.children:
|
52 |
+
return f"{self.value}({', '.join(str(child) for child in self.children)})"
|
53 |
+
else:
|
54 |
+
return str(self.value)
|
55 |
+
|
56 |
+
def evaluate(self, input_grid):
|
57 |
+
if not self.children:
|
58 |
+
if self.value == "input_grid":
|
59 |
+
return input_grid
|
60 |
+
else:
|
61 |
+
raise ValueError(f"Unknown terminal: {self.value}")
|
62 |
+
else:
|
63 |
+
child_values = [child.evaluate(input_grid) for child in self.children]
|
64 |
+
func_data = FUNCTIONS_dictionary.get(self.value)
|
65 |
+
if func_data is None:
|
66 |
+
raise ValueError(f"Unknown function: {self.value}")
|
67 |
+
func, _ = func_data
|
68 |
+
return func(*child_values)
|
69 |
+
|
70 |
+
def generate_random_program(max_depth, current_depth=0):
|
71 |
+
if current_depth >= max_depth or (current_depth > 0 and random.random() < 0.2):
|
72 |
+
terminal = random.choice(TERMINALS)
|
73 |
+
return Node(terminal[0])
|
74 |
+
else:
|
75 |
+
func_name, (func, arity) = random.choice(list(FUNCTIONS_dictionary.items()))
|
76 |
+
children = [generate_random_program(max_depth, current_depth + 1) for _ in range(arity)]
|
77 |
+
return Node(func_name, children)
|
78 |
+
|
79 |
+
def get_all_nodes(program):
|
80 |
+
nodes = [program]
|
81 |
+
for child in program.children:
|
82 |
+
nodes.extend(get_all_nodes(child))
|
83 |
+
return nodes
|
84 |
+
|
85 |
+
class Generation:
|
86 |
+
def __init__(self, best_fitness, population, mutation_rate, crossover_rate, max_depth):
|
87 |
+
self.best_fitness = best_fitness
|
88 |
+
self.population = population
|
89 |
+
self.mutation_rate = mutation_rate
|
90 |
+
self.crossover_rate = crossover_rate
|
91 |
+
self.max_depth = max_depth
|
92 |
+
|
93 |
+
def to_dict(self):
|
94 |
+
return {
|
95 |
+
"best_fitness": self.best_fitness,
|
96 |
+
"population": [str(individual) for individual in self.population]
|
97 |
+
}
|
concept--main/Vit_concept.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
import json
|
4 |
+
import torch
|
5 |
+
import torch.nn.functional as F
|
6 |
+
from transformers import AutoTokenizer, T5Config
|
7 |
+
from torch.nn import CrossEntropyLoss
|
8 |
+
from custom_t5_vit import CustomT5ForConditionalGeneration
|
9 |
+
from GP import genetic_programming
|
10 |
+
from Nods import FUNCTIONS_dictionary
|
11 |
+
from task_loader import *
|
12 |
+
import os
|
13 |
+
|
14 |
+
# Get the base directory where the current script is running
|
15 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
16 |
+
|
17 |
+
# Build relative paths
|
18 |
+
TOKENIZER_PATH = os.path.join(BASE_DIR, "tokenizer_vs22_extendarctokens")
|
19 |
+
MODEL_SAVE_PATH_1 = os.path.join(BASE_DIR, "model", "final_cls_modell.pt")
|
20 |
+
|
21 |
+
print("Loading tokenizer from:", TOKENIZER_PATH)
|
22 |
+
print("Loading model from:", MODEL_SAVE_PATH_1)
|
23 |
+
|
24 |
+
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH)
|
25 |
+
class CustomT5Config(T5Config):
|
26 |
+
def __init__(self, PE_mix_strategy="default", use_objidx="yes",
|
27 |
+
grid_max_height=33, grid_max_width=34, **kwargs):
|
28 |
+
super().__init__(**kwargs)
|
29 |
+
self.PE_mix_strategy = PE_mix_strategy
|
30 |
+
self.use_objidx = use_objidx
|
31 |
+
self.grid_max_height = grid_max_height
|
32 |
+
self.grid_max_width = grid_max_width
|
33 |
+
config = CustomT5Config(
|
34 |
+
vocab_size=len(tokenizer),
|
35 |
+
d_model=128,
|
36 |
+
num_layers=3,
|
37 |
+
num_decoder_layers=3,
|
38 |
+
num_heads=8,
|
39 |
+
d_ff=256,
|
40 |
+
dropout_rate=0.1,
|
41 |
+
pad_token_id=tokenizer.pad_token_id,
|
42 |
+
eos_token_id=tokenizer.eos_token_id
|
43 |
+
)
|
44 |
+
class ConceptDetector(torch.nn.Module):
|
45 |
+
def __init__(self, config, num_classes):
|
46 |
+
super().__init__()
|
47 |
+
self.model = CustomT5ForConditionalGeneration(config)
|
48 |
+
self.classifier_head = torch.nn.Linear(config.d_model, num_classes)
|
49 |
+
self.loss_fn = CrossEntropyLoss()
|
50 |
+
def forward(self, input_ids, attention_mask):
|
51 |
+
encoder_outputs = self.model.encoder(
|
52 |
+
input_ids=input_ids,
|
53 |
+
attention_mask=attention_mask
|
54 |
+
)
|
55 |
+
pooled_output = encoder_outputs.last_hidden_state[:, 0, :]
|
56 |
+
logits = self.classifier_head(pooled_output)
|
57 |
+
probs = F.softmax(logits, dim=1)
|
58 |
+
return probs
|
59 |
+
def load_model(model_path):
|
60 |
+
print(f"Loading model from {model_path}...")
|
61 |
+
checkpoint = torch.load(model_path, map_location=torch.device("cpu"))
|
62 |
+
num_classes = checkpoint["classifier_head.weight"].shape[0]
|
63 |
+
print(f"Detected `num_classes`: {num_classes}")
|
64 |
+
model = ConceptDetector(config=config, num_classes=num_classes)
|
65 |
+
model.load_state_dict(checkpoint)
|
66 |
+
model.eval()
|
67 |
+
return model
|
68 |
+
model = load_model(MODEL_SAVE_PATH_1)
|
69 |
+
def replace_digits_with_arc(grid):
|
70 |
+
return [[f'<arc_{num}>' for num in row] for row in grid]
|
71 |
+
def pad_2d_list(grid, pad_token='<arc_pad>', target_size=32):
|
72 |
+
padded_grid = [row + [pad_token] * (target_size - len(row)) for row in grid]
|
73 |
+
while len(padded_grid) < target_size:
|
74 |
+
padded_grid.append([pad_token] * target_size)
|
75 |
+
return padded_grid
|
76 |
+
def reformat_arc_tokens(grid):
|
77 |
+
padded_tokens_2d = pad_2d_list(grid)
|
78 |
+
flattened_tokens = [token for row in padded_tokens_2d for token in row]
|
79 |
+
return " ".join(flattened_tokens)
|
80 |
+
def preprocess_for_inference(input_grid, output_grid):
|
81 |
+
input_grid = replace_digits_with_arc(input_grid)
|
82 |
+
output_grid = replace_digits_with_arc(output_grid)
|
83 |
+
input_tokens = "<s> Input Grid: " + reformat_arc_tokens(input_grid) + " </s>"
|
84 |
+
output_tokens = " Output Grid: " + reformat_arc_tokens(output_grid) + " </s>"
|
85 |
+
return input_tokens + output_tokens
|
86 |
+
# Concept Label Mapping
|
87 |
+
CONCEPT_LABELS = {'Above_below': 0, 'Below_row_line': 1, 'Center': 2, 'Copy': 3, 'Horizontal_vertical': 4, 'Inside_outside': 5, 'Remove_below_horizontal_line': 6}
|
88 |
+
|
89 |
+
CONCEPT_LABELS_INV = {v: k for k, v in CONCEPT_LABELS.items()}
|
90 |
+
|
91 |
+
# Map ViT Concept to GP Function
|
92 |
+
CONCEPT_TO_FUNCTION_MAP = {
|
93 |
+
'Center': 'find_center_pixel',
|
94 |
+
'Copy': 'identity',
|
95 |
+
'Above_below': 'flip_horizontal',
|
96 |
+
'color_top_part': 'flip_vertical',
|
97 |
+
'Horizontal_vertical':'Horizontal_vertical',
|
98 |
+
|
99 |
+
}
|
100 |
+
def run_inference(model, input_grid, output_grid):
|
101 |
+
formatted_input = preprocess_for_inference(input_grid, output_grid)
|
102 |
+
encoded = tokenizer(formatted_input, return_tensors="pt")
|
103 |
+
with torch.no_grad():
|
104 |
+
probs = model(encoded["input_ids"], encoded["attention_mask"])
|
105 |
+
predicted_class_index = torch.argmax(probs, dim=1).item()
|
106 |
+
concept_label = CONCEPT_LABELS_INV.get(predicted_class_index, "Unknown Concept")
|
107 |
+
print(f"Predicted class index: {predicted_class_index}")
|
108 |
+
print(f"Predicted concept: {concept_label}")
|
109 |
+
gp_function_name = CONCEPT_TO_FUNCTION_MAP.get(concept_label, None)
|
110 |
+
if gp_function_name is None:
|
111 |
+
print(f"Warning: No matching GP function found for concept `{concept_label}`.")
|
112 |
+
return concept_label, None
|
113 |
+
mapped_function = FUNCTIONS_dictionary.get(gp_function_name, None)
|
114 |
+
|
115 |
+
return concept_label, mapped_function
|
116 |
+
if __name__ == "__main__":
|
117 |
+
# Path to your JSON file
|
118 |
+
JSON_DATA_PATH = r"C:\Users\gebre\OneDrive - GIST\문서\KakaoTalk Downloads\GPARC_concept_with_vit\GPARC\SRC\data\AboveBelow3.json"
|
119 |
+
|
120 |
+
# Load JSON data
|
121 |
+
with open(JSON_DATA_PATH, "r") as f:
|
122 |
+
data = json.load(f)
|
123 |
+
|
124 |
+
# Loop through both train and test sets
|
125 |
+
results = []
|
126 |
+
|
127 |
+
for split_name in ["train", "test"]:
|
128 |
+
if split_name in data:
|
129 |
+
print(f"\nRunning inference on `{split_name}` set...")
|
130 |
+
split_results = []
|
131 |
+
for sample in data[split_name]:
|
132 |
+
input_grid = sample["input"]
|
133 |
+
output_grid = sample["output"]
|
134 |
+
predicted_label, mapped_function = run_inference(model, input_grid, output_grid)
|
135 |
+
split_results.append({
|
136 |
+
"input": input_grid,
|
137 |
+
"output": output_grid,
|
138 |
+
"predicted_label": predicted_label,
|
139 |
+
"mapped_function": str(mapped_function) # in case it's a callable
|
140 |
+
})
|
141 |
+
results.append({
|
142 |
+
"split": split_name,
|
143 |
+
"predictions": split_results
|
144 |
+
})
|
145 |
+
|
146 |
+
# Optionally: save the result to a JSON file
|
147 |
+
with open("inference_results.json", "w") as f:
|
148 |
+
json.dump(results, f, indent=2)
|
149 |
+
|
150 |
+
print("\nInference completed. Results saved to `inference_results.json`.")
|
151 |
+
|
152 |
+
|
153 |
+
|
concept--main/app.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import json
|
3 |
+
from Vit_concept import run_inference, model
|
4 |
+
from GP import genetic_programming
|
5 |
+
|
6 |
+
st.title(" Concept Guieded GP_ARC Solver")
|
7 |
+
st.write("Upload your ARC task (JSON format) and let the system solve it.")
|
8 |
+
|
9 |
+
uploaded_file = st.file_uploader("Upload your ARC task JSON file", type=["json"])
|
10 |
+
|
11 |
+
if uploaded_file:
|
12 |
+
data = json.load(uploaded_file)
|
13 |
+
|
14 |
+
input_output_pairs = []
|
15 |
+
predicted_HLCs = []
|
16 |
+
|
17 |
+
st.write("### Running Recognition Module...")
|
18 |
+
|
19 |
+
for sample in data.get("train", []): # or 'test'
|
20 |
+
input_grid = sample["input"]
|
21 |
+
output_grid = sample["output"]
|
22 |
+
|
23 |
+
st.write("#### Input Grid:")
|
24 |
+
st.text(input_grid)
|
25 |
+
st.write("#### Output Grid:")
|
26 |
+
st.text(output_grid)
|
27 |
+
|
28 |
+
concept_label, _ = run_inference(model, input_grid, output_grid)
|
29 |
+
st.write(f" Predicted Concept: `{concept_label}`")
|
30 |
+
|
31 |
+
predicted_HLCs.append(concept_label)
|
32 |
+
input_output_pairs.append((input_grid, output_grid))
|
33 |
+
|
34 |
+
predicted_HLCs = list(set(predicted_HLCs))
|
35 |
+
st.write("### Predicted High-Level Concepts:", predicted_HLCs)
|
36 |
+
|
37 |
+
if st.button("Run Genetic Programming"):
|
38 |
+
st.write("Running Genetic Programming... (this may take a few minutes)")
|
39 |
+
best_program, generations = genetic_programming(
|
40 |
+
input_output_pairs=input_output_pairs,
|
41 |
+
population_size=300,
|
42 |
+
generations=500,
|
43 |
+
mutation_rate=0.2,
|
44 |
+
crossover_rate=0.7,
|
45 |
+
max_depth=3,
|
46 |
+
predicted_HLCs=predicted_HLCs
|
47 |
+
)
|
48 |
+
st.success(" GP Completed!")
|
49 |
+
st.write("### Best Program Found:")
|
50 |
+
st.code(str(best_program))
|
51 |
+
|
52 |
+
|
53 |
+
|
54 |
+
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
|
59 |
+
|
60 |
+
|
61 |
+
|
62 |
+
|
63 |
+
|
64 |
+
|
65 |
+
|
66 |
+
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
|
71 |
+
|
72 |
+
|
73 |
+
|
74 |
+
|
75 |
+
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
|
80 |
+
|
81 |
+
|
82 |
+
|
concept--main/custom_t5_vit.py
ADDED
@@ -0,0 +1,1833 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Custom ViT from T5
|
2 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/modeling_t5.py
|
3 |
+
|
4 |
+
from transformers.models.t5.modeling_t5 import (
|
5 |
+
T5Model,
|
6 |
+
T5Config,
|
7 |
+
T5Stack,
|
8 |
+
T5PreTrainedModel,
|
9 |
+
T5Block,
|
10 |
+
T5LayerNorm,
|
11 |
+
T5LayerFF,
|
12 |
+
T5LayerSelfAttention,
|
13 |
+
T5Attention,
|
14 |
+
T5LayerCrossAttention,
|
15 |
+
)
|
16 |
+
|
17 |
+
from transformers.modeling_outputs import (
|
18 |
+
CausalLMOutputWithPast,
|
19 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
20 |
+
SequenceClassifierOutputWithPast,
|
21 |
+
TokenClassifierOutput,
|
22 |
+
)
|
23 |
+
|
24 |
+
|
25 |
+
|
26 |
+
import math
|
27 |
+
import torch
|
28 |
+
from torch import nn
|
29 |
+
from torch.nn.parameter import Parameter
|
30 |
+
import torch.nn.functional as F
|
31 |
+
#encoder related code starts here
|
32 |
+
# Unified Vision Transformer Embedding class
|
33 |
+
class VisionTransformerEmbedding(nn.Module):
|
34 |
+
def __init__(self, embed_dim, config):
|
35 |
+
super(VisionTransformerEmbedding, self).__init__()
|
36 |
+
self.config = config
|
37 |
+
self.embed_dim = embed_dim
|
38 |
+
|
39 |
+
# Learnable scaling factors for the learnable normalization option
|
40 |
+
if self.config.PE_mix_strategy in ['learnable_scaling_vec', 'weighted_sum_vec', 'weighted_sum_no_norm_vec']:
|
41 |
+
self.position_scale = nn.Parameter(torch.ones(1, embed_dim))
|
42 |
+
self.input_weight = nn.Parameter(torch.ones(1,embed_dim))
|
43 |
+
self.position_weight = nn.Parameter(torch.ones(1,embed_dim))
|
44 |
+
|
45 |
+
if self.config.PE_mix_strategy in ['learnable_scaling', 'weighted_sum', 'weighted_sum_no_norm']:
|
46 |
+
self.position_scale = nn.Parameter(torch.ones(1))
|
47 |
+
self.input_weight = nn.Parameter(torch.ones(1))
|
48 |
+
self.position_weight = nn.Parameter(torch.ones(1))
|
49 |
+
|
50 |
+
# Positional attention mechanism for the positional attention option
|
51 |
+
if self.config.PE_mix_strategy == 'positional_attention':
|
52 |
+
self.attention = nn.MultiheadAttention(embed_dim, num_heads=8)
|
53 |
+
|
54 |
+
# Layer normalization for the layer normalization option
|
55 |
+
if self.config.PE_mix_strategy == 'layer_norm':
|
56 |
+
self.layer_norm = nn.LayerNorm(embed_dim)
|
57 |
+
|
58 |
+
def forward(self, inputs_embeds, position_embeds):
|
59 |
+
strategy = self.config.PE_mix_strategy
|
60 |
+
|
61 |
+
if strategy == 'hardcoded_normalization':
|
62 |
+
inputs_embeds_norm = F.normalize(inputs_embeds, p=2, dim=-1)
|
63 |
+
position_embeds_norm = F.normalize(position_embeds, p=2, dim=-1)
|
64 |
+
output_embeds = inputs_embeds_norm + position_embeds_norm
|
65 |
+
|
66 |
+
elif strategy in ['learnable_scaling','learnable_scaling_vec']:
|
67 |
+
scaled_position_embeds = self.position_scale * position_embeds
|
68 |
+
output_embeds = inputs_embeds + scaled_position_embeds
|
69 |
+
|
70 |
+
elif strategy in ['weighted_sum','weighted_sum_vec']:
|
71 |
+
inputs_embeds_norm = F.normalize(inputs_embeds, p=2, dim=-1)
|
72 |
+
position_embeds_norm = F.normalize(position_embeds, p=2, dim=-1)
|
73 |
+
output_embeds = (self.input_weight * inputs_embeds_norm) + (self.position_weight * position_embeds_norm)
|
74 |
+
|
75 |
+
elif strategy in ['weighted_sum_no_norm','weighted_sum_no_norm_vec']:
|
76 |
+
# Directly apply the weights without normalization
|
77 |
+
output_embeds = (self.input_weight * inputs_embeds) + (self.position_weight * position_embeds)
|
78 |
+
|
79 |
+
elif strategy == 'positional_attention':
|
80 |
+
# Expanding position_embeds to match the batch size of inputs_embeds
|
81 |
+
position_embeds_expanded = position_embeds.expand(inputs_embeds.shape[0], -1, -1)
|
82 |
+
|
83 |
+
# Ensure the inputs are in the correct shape for MultiheadAttention (3D: [seq_len, batch_size, embed_dim])
|
84 |
+
inputs_embeds_reshaped = inputs_embeds.transpose(0, 1) # [batch_size, seq_len, embed_dim] -> [seq_len, batch_size, embed_dim]
|
85 |
+
position_embeds_reshaped = position_embeds_expanded.transpose(0, 1) # [batch_size, seq_len, embed_dim] -> [seq_len, batch_size, embed_dim]
|
86 |
+
|
87 |
+
attn_output, _ = self.attention(inputs_embeds_reshaped, position_embeds_reshaped, position_embeds_reshaped)
|
88 |
+
output_embeds = inputs_embeds_reshaped + attn_output
|
89 |
+
|
90 |
+
# Transpose back to original shape
|
91 |
+
output_embeds = output_embeds.transpose(0, 1) # [seq_len, batch_size, embed_dim] -> [batch_size, seq_len, embed_dim]
|
92 |
+
|
93 |
+
elif strategy == 'layer_norm':
|
94 |
+
combined_embeds = inputs_embeds + position_embeds
|
95 |
+
# Default comes with Learnable Scaling and Shifting
|
96 |
+
output_embeds = self.layer_norm(combined_embeds)
|
97 |
+
|
98 |
+
elif strategy == 'default':
|
99 |
+
output_embeds = inputs_embeds + position_embeds
|
100 |
+
|
101 |
+
else:
|
102 |
+
raise ValueError(f"Unsupported PE_mix_strategy: {strategy}")
|
103 |
+
|
104 |
+
return output_embeds
|
105 |
+
|
106 |
+
|
107 |
+
# https://github.com/McGill-NLP/length-generalization/blob/main/src/models/custom_t5_decoder_only.py
|
108 |
+
class PositionalEmbedding(nn.Module):
|
109 |
+
def __init__(self, demb):
|
110 |
+
super().__init__()
|
111 |
+
|
112 |
+
self.demb = demb
|
113 |
+
|
114 |
+
inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb))
|
115 |
+
self.register_buffer("inv_freq", inv_freq)
|
116 |
+
|
117 |
+
def forward(self, pos_seq, bsz=None):
|
118 |
+
sinusoid_inp = torch.ger(pos_seq, self.inv_freq)
|
119 |
+
pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)
|
120 |
+
|
121 |
+
if bsz is not None:
|
122 |
+
return pos_emb[None, :, :].expand(bsz, -1, -1)
|
123 |
+
else:
|
124 |
+
return pos_emb[None, :, :]
|
125 |
+
|
126 |
+
|
127 |
+
class FixedAbsolutePositionalEmbedding(nn.Module):
|
128 |
+
def __init__(self, dim):
|
129 |
+
super().__init__()
|
130 |
+
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
|
131 |
+
t = torch.arange(16384).type_as(inv_freq)
|
132 |
+
sinusoid_inp = torch.einsum("i , j -> i j", t, inv_freq)
|
133 |
+
emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1)
|
134 |
+
self.embed = nn.Embedding.from_pretrained(emb, freeze=True)
|
135 |
+
|
136 |
+
def forward(self, position_ids: torch.Tensor):
|
137 |
+
return self.embed(position_ids.long())
|
138 |
+
|
139 |
+
|
140 |
+
class FixedRotaryPositionalEmbedding(nn.Module):
|
141 |
+
def __init__(
|
142 |
+
self, rotary_dim: int, rotary_base: int = 10000, max_position: int = 16384
|
143 |
+
):
|
144 |
+
super().__init__()
|
145 |
+
# This is an inverse frequency tensor
|
146 |
+
# Each dimension has a higher denominator than the previous one
|
147 |
+
# So, the frequency will be lower for higher dimensions
|
148 |
+
inv_freq = 1.0 / (
|
149 |
+
rotary_base ** (torch.arange(0, rotary_dim, 2).float() / rotary_dim)
|
150 |
+
) # [rotary_dim/2]
|
151 |
+
|
152 |
+
# Now, we create frequencies for each position
|
153 |
+
t = torch.arange(max_position, device=inv_freq.device, dtype=inv_freq.dtype)
|
154 |
+
freqs = torch.einsum("i,j->ij", t, inv_freq) # [max_position, rotary_dim/2]
|
155 |
+
|
156 |
+
sins = torch.sin(freqs)
|
157 |
+
coss = torch.cos(freqs)
|
158 |
+
|
159 |
+
emb = torch.cat([sins, coss], dim=-1) # [max_position, rotary_dim]
|
160 |
+
self.embed = nn.Embedding.from_pretrained(emb, freeze=True)
|
161 |
+
|
162 |
+
def forward(self, position_ids: torch.Tensor):
|
163 |
+
return self.embed(position_ids.long())
|
164 |
+
|
165 |
+
def fixed_pos_embedding(x, seq_dim=1, seq_len=None):
|
166 |
+
dim = x.shape[-1]
|
167 |
+
if seq_len is None:
|
168 |
+
seq_len = x.shape[seq_dim]
|
169 |
+
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim))
|
170 |
+
sinusoid_inp = (
|
171 |
+
torch.einsum("i , j -> i j", torch.arange(seq_len), inv_freq)
|
172 |
+
.to(x.device)
|
173 |
+
.float()
|
174 |
+
)
|
175 |
+
return torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)
|
176 |
+
|
177 |
+
|
178 |
+
def rotate_every_two(x):
|
179 |
+
"""
|
180 |
+
Example: [a, b, c, d] -> [-b, a, -d, c]
|
181 |
+
"""
|
182 |
+
x1 = x[:, :, :, ::2]
|
183 |
+
x2 = x[:, :, :, 1::2]
|
184 |
+
x = torch.stack((-x2, x1), axis=-1)
|
185 |
+
return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)')
|
186 |
+
|
187 |
+
|
188 |
+
def apply_rotary_pos_emb(x, sincos, offset=0):
|
189 |
+
sin, cos = map(
|
190 |
+
lambda t: t[None, offset : x.shape[1] + offset, None, :].repeat_interleave(
|
191 |
+
2, 3
|
192 |
+
),
|
193 |
+
sincos,
|
194 |
+
)
|
195 |
+
# einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], "n d -> () n () (d j)", j=2)
|
196 |
+
return (x * cos) + (rotate_every_two(x) * sin)
|
197 |
+
|
198 |
+
|
199 |
+
def apply_rotary_pos_emb_new(x, sincos, offset=0):
|
200 |
+
sin, cos = map(
|
201 |
+
lambda t: t[:, :, None, :].repeat_interleave(2, 3),
|
202 |
+
sincos,
|
203 |
+
)
|
204 |
+
# einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], "n d -> () n () (d j)", j=2)
|
205 |
+
return (x * cos) + (rotate_every_two(x) * sin)
|
206 |
+
|
207 |
+
|
208 |
+
class CustomT5Attention(T5Attention):
|
209 |
+
def __init__(self, config: T5Config, has_relative_attention_bias=False, pos_enc_type="RPE", attn_type="self", rpe_type="abs"):
|
210 |
+
super().__init__(config)
|
211 |
+
|
212 |
+
#self.pos_enc_type = pos_enc_type
|
213 |
+
# Alibi-rpe_sbias
|
214 |
+
if "-" in pos_enc_type:
|
215 |
+
pos_enc_split = pos_enc_type.split("-")
|
216 |
+
self.pos_enc_type = pos_enc_split[0]
|
217 |
+
self.struct_attn_type = pos_enc_split[1]
|
218 |
+
else:
|
219 |
+
self.pos_enc_type = pos_enc_type
|
220 |
+
self.struct_attn_type = ""
|
221 |
+
|
222 |
+
self.d_head = config.d_kv
|
223 |
+
self.attn_type = attn_type
|
224 |
+
self.rpe_type = rpe_type
|
225 |
+
self.has_relative_attention_bias = has_relative_attention_bias
|
226 |
+
|
227 |
+
if self.pos_enc_type == "RoPE":
|
228 |
+
self.rotary_dim = None
|
229 |
+
if getattr(config, "rotary_dim", None) is not None:
|
230 |
+
self.rotary_dim = config.rotary_dim
|
231 |
+
self.rotary_dim = int(0.25 * self.d_head)
|
232 |
+
|
233 |
+
# Get the device from the configuration
|
234 |
+
#device = torch.device("cuda" if torch.cuda.is_available() and config.device == 'cuda' else "cpu")
|
235 |
+
if self.pos_enc_type != "RPE":
|
236 |
+
self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)
|
237 |
+
device = self.relative_attention_bias.weight.device
|
238 |
+
|
239 |
+
#print(f"has_relative_attention_bias:{has_relative_attention_bias}")
|
240 |
+
if self.has_relative_attention_bias:
|
241 |
+
if self.pos_enc_type == "RPE":
|
242 |
+
self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)
|
243 |
+
elif self.pos_enc_type in ["Alibi","APEAlibi"]:
|
244 |
+
#print(f"device:{device}")
|
245 |
+
if self.struct_attn_type == "duo":
|
246 |
+
self.slopes_l = torch.Tensor(self.get_slopes(self.n_heads)).to(device)*-1
|
247 |
+
self.slopes_r = torch.Tensor(self.get_slopes(self.n_heads)).to(device)*-1
|
248 |
+
elif self.struct_attn_type == "rpe_sbias":
|
249 |
+
self.slopes = torch.Tensor(self.get_slopes(self.n_heads)).to(device)*-1
|
250 |
+
self.struct_slopes = torch.Tensor(self.get_slopes(self.n_heads)).to(device)*-1
|
251 |
+
else:
|
252 |
+
self.slopes = torch.Tensor(self.get_slopes(self.n_heads)).to(device)*-1
|
253 |
+
elif self.pos_enc_type == "KerpleLog":
|
254 |
+
self.eps = 1e-2
|
255 |
+
self.bias_p = self.get_kerple_parameter(2, 'uniform',device)
|
256 |
+
self.bias_a = self.get_kerple_parameter(1, 'uniform',device)
|
257 |
+
elif self.pos_enc_type in ["NoPE", "LearnedAPE", "SinusoidalAPE","SinusoidalAPE2D", "RoPE"]:
|
258 |
+
#self.relative_attention_bias = None # No positional encoding bias
|
259 |
+
pass
|
260 |
+
else:
|
261 |
+
self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)
|
262 |
+
# Add more types if necessary
|
263 |
+
|
264 |
+
# Allocate weights and initialize.
|
265 |
+
# The kernel has the form -p*log(1+a*|m-n|)
|
266 |
+
def get_kerple_parameter(self,scale, init_method, device):
|
267 |
+
if init_method == 'ones':
|
268 |
+
return Parameter(torch.ones(
|
269 |
+
self.n_heads,
|
270 |
+
device=device,
|
271 |
+
)[:,None,None]*scale )
|
272 |
+
elif init_method == 'uniform':
|
273 |
+
return Parameter(torch.rand(
|
274 |
+
self.n_heads,
|
275 |
+
device=device,
|
276 |
+
)[:,None,None]*scale )
|
277 |
+
|
278 |
+
# https://github.com/ofirpress/attention_with_linear_biases/issues/5
|
279 |
+
def get_slopes(self, n):
|
280 |
+
def get_slopes_power_of_2(n):
|
281 |
+
start = (2**(-2**-(math.log2(n)-3)))
|
282 |
+
ratio = start
|
283 |
+
return [start*ratio**i for i in range(n)]
|
284 |
+
|
285 |
+
if math.log2(n).is_integer():
|
286 |
+
return get_slopes_power_of_2(n) #In the paper, we only train models that have 2^a heads for some a. This function has
|
287 |
+
else: #some good properties that only occur when the input is a power of 2. To maintain that even
|
288 |
+
closest_power_of_2 = 2**math.floor(math.log2(n)) #when the number of heads is not a power of 2, we use this workaround.
|
289 |
+
return get_slopes_power_of_2(closest_power_of_2) + self.get_slopes(2*closest_power_of_2)[0::2][:n-closest_power_of_2]
|
290 |
+
|
291 |
+
def compute_struct_bias(self, query_length, key_length, device=None, relative_position=None):
|
292 |
+
"""Compute binned relative position bias"""
|
293 |
+
if device is None:
|
294 |
+
device = self.relative_attention_bias.weight.device
|
295 |
+
|
296 |
+
#print("#### Compute bias")
|
297 |
+
if self.pos_enc_type in ["NoPE", "LearnedAPE", "SinusoidalAPE","SinusoidalAPE2D", "RoPE"]:
|
298 |
+
return torch.zeros((1, self.n_heads, query_length, key_length), device=device)
|
299 |
+
#elif self.pos_enc_type == "Alibi":
|
300 |
+
elif self.pos_enc_type in ["Alibi","APEAlibi"]:
|
301 |
+
if self.struct_attn_type == "duo":
|
302 |
+
if relative_position is None:
|
303 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
304 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
305 |
+
relative_position = memory_position - context_position # shape (query_length, key_length)
|
306 |
+
|
307 |
+
if self.rpe_type == "abs":
|
308 |
+
relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.n_heads, -1,-1)
|
309 |
+
else:
|
310 |
+
relative_position = relative_position.unsqueeze(0).expand(self.n_heads, -1,-1)
|
311 |
+
|
312 |
+
self.slopes_l = self.slopes_l.to(device)
|
313 |
+
self.slopes_r = self.slopes_r.to(device)
|
314 |
+
|
315 |
+
alibi_left = self.slopes_l.unsqueeze(1).unsqueeze(1) * relative_position
|
316 |
+
alibi_right = self.slopes_r.unsqueeze(1).unsqueeze(1) * relative_position
|
317 |
+
|
318 |
+
values = torch.triu(alibi_right) + torch.tril(alibi_left)
|
319 |
+
values = values.view(1, self.n_heads, query_length, key_length) # shape (1, num_heads, query_length, key_length)
|
320 |
+
return values
|
321 |
+
else:
|
322 |
+
if relative_position is None:
|
323 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
324 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
325 |
+
relative_position = memory_position - context_position # shape (query_length, key_length)
|
326 |
+
#else:
|
327 |
+
#Simple case here, every tree has the same distance matrix
|
328 |
+
#relative_position = relative_position.repeat(1, self.n_heads, 1, 1)
|
329 |
+
|
330 |
+
if self.rpe_type == "abs":
|
331 |
+
relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.n_heads, -1,-1)
|
332 |
+
else:
|
333 |
+
relative_position = relative_position.unsqueeze(0).expand(self.n_heads, -1,-1)
|
334 |
+
|
335 |
+
#print(f"relative_position.shape:{relative_position.shape}")
|
336 |
+
#print(f"relative_position:{relative_position}")
|
337 |
+
self.struct_slopes = self.struct_slopes.to(device)
|
338 |
+
|
339 |
+
values = self.struct_slopes.unsqueeze(1).unsqueeze(1) * relative_position
|
340 |
+
values = values.view(1, self.n_heads, query_length, key_length) # shape (1, num_heads, query_length, key_length)
|
341 |
+
return values
|
342 |
+
elif self.pos_enc_type == "KerpleLog":
|
343 |
+
if relative_position is None:
|
344 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
345 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
346 |
+
relative_position = memory_position - context_position # shape (query_length, key_length)
|
347 |
+
if self.rpe_type == "abs":
|
348 |
+
relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.n_heads, -1,-1)
|
349 |
+
else:
|
350 |
+
relative_position = relative_position.unsqueeze(0).expand(self.n_heads, -1,-1)
|
351 |
+
|
352 |
+
self.bias_p.data = self.bias_p.data.clamp(min=self.eps)
|
353 |
+
self.bias_a.data = self.bias_a.data.clamp(min=self.eps)
|
354 |
+
|
355 |
+
self.bias_p = self.bias_p.to(device)
|
356 |
+
self.bias_a = self.bias_a.to(device)
|
357 |
+
|
358 |
+
values = -self.bias_p*torch.log(1+self.bias_a*relative_position) # log kernel # shape (num_heads, query_length, key_length)
|
359 |
+
values = values.unsqueeze(0) # shape (1, num_heads, query_length, key_length)
|
360 |
+
return values
|
361 |
+
else:
|
362 |
+
#context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
363 |
+
#memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
364 |
+
#relative_position = memory_position - context_position # shape (query_length, key_length)
|
365 |
+
if relative_position is None:
|
366 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
367 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
368 |
+
relative_position = memory_position - context_position # shape (query_length, key_length)
|
369 |
+
relative_position_bucket = self._relative_position_bucket(
|
370 |
+
relative_position, # shape (query_length, key_length)
|
371 |
+
bidirectional=(not self.is_decoder),
|
372 |
+
num_buckets=self.relative_attention_num_buckets,
|
373 |
+
max_distance=self.relative_attention_max_distance,
|
374 |
+
)
|
375 |
+
values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
|
376 |
+
values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length)
|
377 |
+
return values
|
378 |
+
|
379 |
+
def compute_bias(self, query_length, key_length, device=None, relative_position=None):
|
380 |
+
"""Compute binned relative position bias"""
|
381 |
+
if device is None:
|
382 |
+
device = self.relative_attention_bias.weight.device
|
383 |
+
|
384 |
+
#print("query_length",query_length)
|
385 |
+
#print("key_length",key_length)
|
386 |
+
|
387 |
+
#print("#### Compute bias")
|
388 |
+
if self.pos_enc_type in ["NoPE", "LearnedAPE", "SinusoidalAPE","SinusoidalAPE2D", "RoPE"]:
|
389 |
+
return torch.zeros((1, self.n_heads, query_length, key_length), device=device)
|
390 |
+
#elif self.pos_enc_type == "Alibi":
|
391 |
+
elif self.pos_enc_type in ["Alibi","APEAlibi"]:
|
392 |
+
if self.struct_attn_type == "duo":
|
393 |
+
relative_position = relative_position.to(device)
|
394 |
+
|
395 |
+
if self.rpe_type == "abs":
|
396 |
+
relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.n_heads, -1,-1)
|
397 |
+
else:
|
398 |
+
relative_position = relative_position.unsqueeze(0).expand(self.n_heads, -1,-1)
|
399 |
+
|
400 |
+
self.slopes_l = self.slopes_l.to(device)
|
401 |
+
self.slopes_r = self.slopes_r.to(device)
|
402 |
+
|
403 |
+
alibi_left = self.slopes_l.unsqueeze(1).unsqueeze(1) * relative_position
|
404 |
+
alibi_right = self.slopes_r.unsqueeze(1).unsqueeze(1) * relative_position
|
405 |
+
|
406 |
+
values = torch.triu(alibi_right) + torch.tril(alibi_left)
|
407 |
+
# Slice the relevant part of the bias before reshaping
|
408 |
+
values = values[:, :query_length, :key_length] # Slicing the tensor before reshaping
|
409 |
+
|
410 |
+
values = values.view(1, self.n_heads, query_length, key_length) # shape (1, num_heads, query_length, key_length)
|
411 |
+
#print(f"values.shape:{values.shape}")
|
412 |
+
|
413 |
+
return values
|
414 |
+
else:
|
415 |
+
if relative_position is None:
|
416 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
417 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
418 |
+
relative_position = memory_position - context_position # shape (query_length, key_length)
|
419 |
+
#else:
|
420 |
+
#Simple case here, every tree has the same distance matrix
|
421 |
+
#relative_position = relative_position.repeat(1, self.n_heads, 1, 1)
|
422 |
+
|
423 |
+
if self.rpe_type == "abs":
|
424 |
+
relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.n_heads, -1,-1)
|
425 |
+
else:
|
426 |
+
relative_position = relative_position.unsqueeze(0).expand(self.n_heads, -1,-1)
|
427 |
+
|
428 |
+
#print(f"relative_position.shape:{relative_position.shape}")
|
429 |
+
#print(f"relative_position:{relative_position}")
|
430 |
+
self.slopes = self.slopes.to(device)
|
431 |
+
|
432 |
+
values = self.slopes.unsqueeze(1).unsqueeze(1) * relative_position
|
433 |
+
values = values.view(1, self.n_heads, query_length, key_length) # shape (1, num_heads, query_length, key_length)
|
434 |
+
return values
|
435 |
+
elif self.pos_enc_type == "KerpleLog":
|
436 |
+
if relative_position is None:
|
437 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
438 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
439 |
+
relative_position = memory_position - context_position # shape (query_length, key_length)
|
440 |
+
if self.rpe_type == "abs":
|
441 |
+
relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.n_heads, -1,-1)
|
442 |
+
else:
|
443 |
+
relative_position = relative_position.unsqueeze(0).expand(self.n_heads, -1,-1)
|
444 |
+
|
445 |
+
self.bias_p.data = self.bias_p.data.clamp(min=self.eps)
|
446 |
+
self.bias_a.data = self.bias_a.data.clamp(min=self.eps)
|
447 |
+
|
448 |
+
self.bias_p = self.bias_p.to(device)
|
449 |
+
self.bias_a = self.bias_a.to(device)
|
450 |
+
|
451 |
+
values = -self.bias_p*torch.log(1+self.bias_a*relative_position) # log kernel # shape (num_heads, query_length, key_length)
|
452 |
+
values = values.unsqueeze(0) # shape (1, num_heads, query_length, key_length)
|
453 |
+
return values
|
454 |
+
else:
|
455 |
+
#context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
456 |
+
#memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
457 |
+
#relative_position = memory_position - context_position # shape (query_length, key_length)
|
458 |
+
if relative_position is None:
|
459 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
460 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
461 |
+
relative_position = memory_position - context_position # shape (query_length, key_length)
|
462 |
+
relative_position_bucket = self._relative_position_bucket(
|
463 |
+
relative_position, # shape (query_length, key_length)
|
464 |
+
bidirectional=(not self.is_decoder),
|
465 |
+
num_buckets=self.relative_attention_num_buckets,
|
466 |
+
max_distance=self.relative_attention_max_distance,
|
467 |
+
)
|
468 |
+
values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
|
469 |
+
values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length)
|
470 |
+
return values
|
471 |
+
|
472 |
+
def forward(
|
473 |
+
self,
|
474 |
+
hidden_states,
|
475 |
+
mask=None,
|
476 |
+
key_value_states=None,
|
477 |
+
position_bias=None,
|
478 |
+
past_key_value=None,
|
479 |
+
layer_head_mask=None,
|
480 |
+
query_length=None,
|
481 |
+
use_cache=False,
|
482 |
+
output_attentions=False,
|
483 |
+
relative_position=None,
|
484 |
+
struct_position_bias=None,
|
485 |
+
):
|
486 |
+
"""
|
487 |
+
Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
|
488 |
+
"""
|
489 |
+
# Input is (batch_size, seq_length, dim)
|
490 |
+
# Mask is (batch_size, key_length) (non-causal) or (batch_size, key_length, key_length)
|
491 |
+
# past_key_value[0] is (batch_size, n_heads, q_len - 1, dim_per_head)
|
492 |
+
batch_size, seq_length = hidden_states.shape[:2]
|
493 |
+
|
494 |
+
|
495 |
+
real_seq_length = seq_length
|
496 |
+
|
497 |
+
if past_key_value is not None:
|
498 |
+
if len(past_key_value) != 2:
|
499 |
+
raise ValueError(
|
500 |
+
f"past_key_value should have 2 past states: keys and values. Got { len(past_key_value)} past states"
|
501 |
+
)
|
502 |
+
real_seq_length += past_key_value[0].shape[2] if query_length is None else query_length
|
503 |
+
|
504 |
+
key_length = real_seq_length if key_value_states is None else key_value_states.shape[1]
|
505 |
+
|
506 |
+
|
507 |
+
def shape(states):
|
508 |
+
"""projection"""
|
509 |
+
return states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2)
|
510 |
+
|
511 |
+
def unshape(states):
|
512 |
+
"""reshape"""
|
513 |
+
return states.transpose(1, 2).contiguous().view(batch_size, -1, self.inner_dim)
|
514 |
+
|
515 |
+
def project(hidden_states, proj_layer, key_value_states, past_key_value):
|
516 |
+
"""projects hidden states correctly to key/query states"""
|
517 |
+
if key_value_states is None:
|
518 |
+
# self-attn
|
519 |
+
# (batch_size, n_heads, seq_length, dim_per_head)
|
520 |
+
hidden_states = shape(proj_layer(hidden_states))
|
521 |
+
elif past_key_value is None:
|
522 |
+
# cross-attn
|
523 |
+
# (batch_size, n_heads, seq_length, dim_per_head)
|
524 |
+
hidden_states = shape(proj_layer(key_value_states))
|
525 |
+
|
526 |
+
if past_key_value is not None:
|
527 |
+
if key_value_states is None:
|
528 |
+
# self-attn
|
529 |
+
# (batch_size, n_heads, key_length, dim_per_head)
|
530 |
+
hidden_states = torch.cat([past_key_value, hidden_states], dim=2)
|
531 |
+
elif past_key_value.shape[2] != key_value_states.shape[1]:
|
532 |
+
# checking that the `sequence_length` of the `past_key_value` is the same as
|
533 |
+
# the provided `key_value_states` to support prefix tuning
|
534 |
+
# cross-attn
|
535 |
+
# (batch_size, n_heads, seq_length, dim_per_head)
|
536 |
+
hidden_states = shape(proj_layer(key_value_states))
|
537 |
+
else:
|
538 |
+
# cross-attn
|
539 |
+
hidden_states = past_key_value
|
540 |
+
return hidden_states
|
541 |
+
|
542 |
+
#print(f"\nattn_type:{self.attn_type}")
|
543 |
+
#print(f"hidden_states.shape:{hidden_states.shape}")
|
544 |
+
#if key_value_states is not None:
|
545 |
+
# print(f"key_value_states.shape:{key_value_states.shape}")
|
546 |
+
#if past_key_value is not None:
|
547 |
+
# print(f"past_key_value[0].shape:{past_key_value[0].shape}")
|
548 |
+
|
549 |
+
# get query states
|
550 |
+
query_states = shape(self.q(hidden_states)) # (batch_size, n_heads, seq_length, dim_per_head)
|
551 |
+
#print(f"query_states.shape (before RoPE): {query_states.shape}") # Check shape before RoPE
|
552 |
+
|
553 |
+
# get key/value states
|
554 |
+
if self.pos_enc_type == "RoPE":
|
555 |
+
#key_states = shape(self.k(hidden_states))
|
556 |
+
#findme
|
557 |
+
key_states = project(
|
558 |
+
hidden_states, self.k, key_value_states, past_key_value[0] if past_key_value is not None else None
|
559 |
+
)
|
560 |
+
|
561 |
+
#print(f"key_states2.shape (before RoPE): {key_states2.shape}")
|
562 |
+
else:
|
563 |
+
key_states = project(
|
564 |
+
hidden_states, self.k, key_value_states, past_key_value[0] if past_key_value is not None else None
|
565 |
+
)
|
566 |
+
|
567 |
+
#print(f"key_states.shape (before RoPE): {key_states.shape}")
|
568 |
+
|
569 |
+
value_states = project(
|
570 |
+
hidden_states, self.v, key_value_states, past_key_value[1] if past_key_value is not None else None
|
571 |
+
)
|
572 |
+
|
573 |
+
attention_output_dict = {}
|
574 |
+
|
575 |
+
#print(f"orig, key_states.shape:{key_states.shape}")
|
576 |
+
#print(f"orig, query_states.shape:{query_states.shape}")
|
577 |
+
|
578 |
+
#print(f"has_relative_attention_bias:{self.has_relative_attention_bias}")
|
579 |
+
#print(f"attn_type:{self.attn_type}")
|
580 |
+
#print(f"pos_enc_type:{self.pos_enc_type}")
|
581 |
+
#print(f"rpe_type:{self.rpe_type}")
|
582 |
+
|
583 |
+
if self.pos_enc_type == "RoPE":
|
584 |
+
r_seq_len = hidden_states.shape[1]
|
585 |
+
r_offset = 0
|
586 |
+
|
587 |
+
if past_key_value is not None:
|
588 |
+
# This is considering seq2seq auto-regressive generation case, while the absolute position is offset by + input_len
|
589 |
+
# Can be turned off to test
|
590 |
+
#print(f"past_key_value[0].shape:{past_key_value[0].shape}")
|
591 |
+
r_offset = past_key_value[0].shape[2]
|
592 |
+
r_seq_len += r_offset
|
593 |
+
|
594 |
+
query_states = query_states.permute(0, 2, 1, 3)
|
595 |
+
key_states = key_states.permute(0, 2, 1, 3)
|
596 |
+
|
597 |
+
if self.rotary_dim is not None:
|
598 |
+
|
599 |
+
k_rot = key_states[:, :, :, : self.rotary_dim]
|
600 |
+
k_pass = key_states[:, :, :, self.rotary_dim :]
|
601 |
+
|
602 |
+
q_rot = query_states[:, :, :, : self.rotary_dim]
|
603 |
+
q_pass = query_states[:, :, :, self.rotary_dim :]
|
604 |
+
|
605 |
+
sincos = fixed_pos_embedding(k_rot, 1, seq_len=r_seq_len)
|
606 |
+
k_rot = apply_rotary_pos_emb(k_rot, sincos, offset=r_offset)
|
607 |
+
q_rot = apply_rotary_pos_emb(q_rot, sincos, offset=r_offset)
|
608 |
+
|
609 |
+
if output_attentions:
|
610 |
+
scores_pass = torch.matmul(
|
611 |
+
q_pass.permute(0, 2, 1, 3),
|
612 |
+
k_pass.permute(0, 2, 1, 3).transpose(3, 2),
|
613 |
+
)
|
614 |
+
attention_output_dict["scores_pass"] = scores_pass
|
615 |
+
|
616 |
+
scores_rot = torch.matmul(
|
617 |
+
q_rot.permute(0, 2, 1, 3),
|
618 |
+
k_rot.permute(0, 2, 1, 3).transpose(3, 2),
|
619 |
+
)
|
620 |
+
attention_output_dict["scores_rot"] = scores_rot
|
621 |
+
|
622 |
+
key_states = torch.cat([k_rot, k_pass], dim=-1)
|
623 |
+
query_states = torch.cat([q_rot, q_pass], dim=-1)
|
624 |
+
else:
|
625 |
+
sincos = fixed_pos_embedding(key_states, 1, seq_len=r_seq_len)
|
626 |
+
key_states = apply_rotary_pos_emb(key_states, sincos, offset=r_offset)
|
627 |
+
query_states = apply_rotary_pos_emb(
|
628 |
+
query_states, sincos, offset=r_offset
|
629 |
+
)
|
630 |
+
|
631 |
+
#print(f"inner,before_permute, key_states.shape:{key_states.shape}")
|
632 |
+
#print(f"inner,before_permute, query_states.shape:{query_states.shape}")
|
633 |
+
"""
|
634 |
+
inner,before_permute, key_states.shape:torch.Size([1, 2, 8, 64])
|
635 |
+
inner,before_permute, query_states.shape:torch.Size([1, 1, 8, 64])
|
636 |
+
"""
|
637 |
+
|
638 |
+
query_states = query_states.permute(0, 2, 1, 3)
|
639 |
+
key_states = key_states.permute(0, 2, 1, 3)
|
640 |
+
|
641 |
+
#Ignore this if it's already taken care of in project(hidden_states, proj_layer, key_value_states, past_key_value)
|
642 |
+
"""
|
643 |
+
if past_key_value is not None:
|
644 |
+
print(f"past_key_value[0].shape before concat: {past_key_value[0].shape}")
|
645 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
646 |
+
"""
|
647 |
+
|
648 |
+
#print(f"inner, key_states.shape:{key_states.shape}")
|
649 |
+
#print(f"inner, key_states.transpose(3, 2).shape:{key_states.transpose(3, 2).shape}")
|
650 |
+
#print(f"inner, query_states.shape:{query_states.shape}")
|
651 |
+
"""
|
652 |
+
# At decoder for 3rd token self-attn
|
653 |
+
attn_type:self
|
654 |
+
hidden_states.shape:torch.Size([1, 1, 128])
|
655 |
+
query_states.shape (before RoPE): torch.Size([1, 8, 1, 64])
|
656 |
+
key_states.shape (before RoPE): torch.Size([1, 8, 2, 64])
|
657 |
+
orig, key_states.shape:torch.Size([1, 8, 2, 64])
|
658 |
+
orig, query_states.shape:torch.Size([1, 8, 1, 64])
|
659 |
+
inner, key_states.shape:torch.Size([1, 8, 3, 64]) <- this should be [1, 8, 2, 64]
|
660 |
+
inner, query_states.shape:torch.Size([1, 8, 1, 64])
|
661 |
+
scores.shape:torch.Size([1, 8, 1, 3])
|
662 |
+
mask.shape:torch.Size([1, 1, 1, 2])
|
663 |
+
"""
|
664 |
+
|
665 |
+
|
666 |
+
scores = torch.matmul(
|
667 |
+
query_states, key_states.transpose(3, 2)
|
668 |
+
) # equivalent of torch.einsum("bnqd,bnkd->bnqk", query_states, key_states), compatible with onnx op>9
|
669 |
+
|
670 |
+
#print(f"scores.shape:{scores.shape}")
|
671 |
+
#scores.shape:torch.Size([480, 8, 64, 64])
|
672 |
+
#mask.shape:torch.Size([480, 1, 1, 64])
|
673 |
+
|
674 |
+
# At 1st layer cross attn
|
675 |
+
# scores.shape:torch.Size([1, 8, 1, 1])!!! for the first token it could be key_length=1 but why seq_length = 1 ??
|
676 |
+
if mask is not None:
|
677 |
+
#print(f"mask.shape:{mask.shape}")
|
678 |
+
#scores += mask # (batch_size, n_heads, seq_length, key_length)
|
679 |
+
#scores = scores+mask # (batch_size, n_heads, seq_length, key_length)
|
680 |
+
expanded_mask = mask.expand_as(scores) # expand mask tensor to all heads
|
681 |
+
#print(f"expanded_mask.shape:{expanded_mask.shape}")
|
682 |
+
#print("mask",mask)
|
683 |
+
#print("expanded_mask",expanded_mask)
|
684 |
+
scores += expanded_mask
|
685 |
+
#print("scores",scores)
|
686 |
+
#print(f"scores.shape:{scores.shape}")
|
687 |
+
#RuntimeError: output with shape [512, 8, 1, 1] doesn't match the broadcast shape [512, 8, 1, 64]
|
688 |
+
|
689 |
+
else:
|
690 |
+
# compute scores
|
691 |
+
scores = torch.matmul(
|
692 |
+
query_states, key_states.transpose(3, 2)
|
693 |
+
) # equivalent of torch.einsum("bnqd,bnkd->bnqk", query_states, key_states), compatible with onnx op>9
|
694 |
+
|
695 |
+
#print(f"scores.shape:{scores.shape}")
|
696 |
+
#scores.shape:torch.Size([480, 8, 64, 64])
|
697 |
+
#print(f"self.attn_type",self.attn_type)
|
698 |
+
|
699 |
+
if self.struct_attn_type == "rpe_sbias":
|
700 |
+
if struct_position_bias is None:
|
701 |
+
if not self.has_relative_attention_bias:
|
702 |
+
#print("not has_relative_attention_bias")
|
703 |
+
struct_position_bias = torch.zeros(
|
704 |
+
(1, self.n_heads, real_seq_length, key_length), device=scores.device, dtype=scores.dtype
|
705 |
+
)
|
706 |
+
if self.gradient_checkpointing and self.training:
|
707 |
+
struct_position_bias.requires_grad = True
|
708 |
+
else:
|
709 |
+
struct_position_bias = self.compute_struct_bias(real_seq_length, key_length, device=scores.device, relative_position=relative_position)
|
710 |
+
|
711 |
+
# if key and values are already calculated
|
712 |
+
# we want only the last query position bias
|
713 |
+
if past_key_value is not None:
|
714 |
+
struct_position_bias = struct_position_bias[:, :, -hidden_states.size(1) :, :]
|
715 |
+
|
716 |
+
#print("struct_position_bias.shape:", position_bias.shape)
|
717 |
+
#struct_position_bias.shape: torch.Size([1, 8, 64, 64])
|
718 |
+
if mask is not None:
|
719 |
+
#print(f"mask.shape:{mask.shape}")
|
720 |
+
#mask.shape:torch.Size([480, 1, 1, 64])
|
721 |
+
struct_position_bias = struct_position_bias + mask # (batch_size, n_heads, seq_length, key_length)
|
722 |
+
#print(f"position_bias.shape:{position_bias.shape}")
|
723 |
+
# torch.Size([480, 8, 64, 64])
|
724 |
+
|
725 |
+
if self.pruned_heads:
|
726 |
+
mask = torch.ones(struct_position_bias.shape[1])
|
727 |
+
mask[list(self.pruned_heads)] = 0
|
728 |
+
struct_position_bias_masked = struct_position_bias[:, mask.bool()]
|
729 |
+
else:
|
730 |
+
struct_position_bias_masked = struct_position_bias
|
731 |
+
|
732 |
+
#print(f"struct_position_bias.shape:{struct_position_bias.shape}")
|
733 |
+
#print(f"struct_position_bias_masked.shape:{struct_position_bias_masked.shape}")
|
734 |
+
|
735 |
+
if position_bias is None:
|
736 |
+
if not self.has_relative_attention_bias:
|
737 |
+
#print("not has_relative_attention_bias")
|
738 |
+
position_bias = torch.zeros(
|
739 |
+
(1, self.n_heads, real_seq_length, key_length), device=scores.device, dtype=scores.dtype
|
740 |
+
)
|
741 |
+
if self.gradient_checkpointing and self.training:
|
742 |
+
position_bias.requires_grad = True
|
743 |
+
else:
|
744 |
+
if self.pos_enc_type in ["Alibi","APEAlibi"]:
|
745 |
+
position_bias = self.compute_bias(real_seq_length, key_length, device=scores.device, relative_position=relative_position)
|
746 |
+
else:
|
747 |
+
if self.struct_attn_type == "rpe_sbias":
|
748 |
+
position_bias = self.compute_bias(real_seq_length, key_length, device=scores.device, relative_position=None)
|
749 |
+
else:
|
750 |
+
position_bias = self.compute_bias(real_seq_length, key_length, device=scores.device, relative_position=None)
|
751 |
+
#print(f"position_bias1.shape:{position_bias.shape}")
|
752 |
+
|
753 |
+
# if key and values are already calculated
|
754 |
+
# we want only the last query position bias
|
755 |
+
if past_key_value is not None:
|
756 |
+
position_bias = position_bias[:, :, -hidden_states.size(1) :, :]
|
757 |
+
|
758 |
+
#print(f"position_bias2.shape:{position_bias.shape}")
|
759 |
+
|
760 |
+
#print("position_bias.shape:", position_bias.shape)
|
761 |
+
#position_bias.shape: torch.Size([1, 8, 64, 64])
|
762 |
+
if mask is not None:
|
763 |
+
#print(f"mask.shape:{mask.shape}")
|
764 |
+
#mask.shape:torch.Size([480, 1, 1, 64])
|
765 |
+
position_bias = position_bias + mask # (batch_size, n_heads, seq_length, key_length)
|
766 |
+
#print(f"masked position_bias.shape:{position_bias.shape}")
|
767 |
+
# torch.Size([480, 8, 64, 64])
|
768 |
+
|
769 |
+
#print(f"position_bias3.shape:{position_bias.shape}")
|
770 |
+
|
771 |
+
if self.pruned_heads:
|
772 |
+
mask = torch.ones(position_bias.shape[1])
|
773 |
+
mask[list(self.pruned_heads)] = 0
|
774 |
+
position_bias_masked = position_bias[:, mask.bool()]
|
775 |
+
else:
|
776 |
+
position_bias_masked = position_bias
|
777 |
+
|
778 |
+
#print(f"position_bias.shape:{position_bias.shape}")
|
779 |
+
#print(f"position_bias_masked.shape:{position_bias_masked.shape}")
|
780 |
+
#print(f"scores.shape:{scores.shape}")
|
781 |
+
|
782 |
+
if self.struct_attn_type == "rpe_sbias" and self.attn_type == "self":
|
783 |
+
scores += position_bias_masked + struct_position_bias_masked
|
784 |
+
else:
|
785 |
+
scores += position_bias_masked
|
786 |
+
|
787 |
+
attn_weights = nn.functional.softmax(scores.float(), dim=-1).type_as(
|
788 |
+
scores
|
789 |
+
) # (batch_size, n_heads, seq_length, key_length)
|
790 |
+
attn_weights = nn.functional.dropout(
|
791 |
+
attn_weights, p=self.dropout, training=self.training
|
792 |
+
) # (batch_size, n_heads, seq_length, key_length)
|
793 |
+
|
794 |
+
# Mask heads if we want to
|
795 |
+
if layer_head_mask is not None:
|
796 |
+
attn_weights = attn_weights * layer_head_mask
|
797 |
+
|
798 |
+
attn_output = unshape(torch.matmul(attn_weights, value_states)) # (batch_size, seq_length, dim)
|
799 |
+
attn_output = self.o(attn_output)
|
800 |
+
|
801 |
+
present_key_value_state = (key_states, value_states) if (self.is_decoder and use_cache) else None
|
802 |
+
"""
|
803 |
+
if self.struct_attn_type == "rpe_sbias":
|
804 |
+
outputs = (attn_output,) + (present_key_value_state,) + (position_bias,) + (struct_position_bias,)
|
805 |
+
else:
|
806 |
+
outputs = (attn_output,) + (present_key_value_state,) + (position_bias,)
|
807 |
+
"""
|
808 |
+
|
809 |
+
outputs = (attn_output,) + (present_key_value_state,) + (position_bias,) + (struct_position_bias,)
|
810 |
+
|
811 |
+
if output_attentions:
|
812 |
+
outputs = outputs + (attn_weights,)
|
813 |
+
return outputs
|
814 |
+
|
815 |
+
|
816 |
+
from transformers.models.t5.modeling_t5 import T5LayerSelfAttention, T5LayerCrossAttention
|
817 |
+
import copy
|
818 |
+
|
819 |
+
class CustomT5LayerSelfAttention(T5LayerSelfAttention):
|
820 |
+
def __init__(self, config, has_relative_attention_bias=False, pos_enc_type="RPE", rpe_type="abs"):
|
821 |
+
super().__init__(config, has_relative_attention_bias)
|
822 |
+
self.pos_enc_type=pos_enc_type
|
823 |
+
self.rpe_type=rpe_type
|
824 |
+
self.SelfAttention = CustomT5Attention(config, has_relative_attention_bias=has_relative_attention_bias, pos_enc_type=pos_enc_type, attn_type="self", rpe_type=rpe_type)
|
825 |
+
self.is_decoder = config.is_decoder
|
826 |
+
|
827 |
+
def forward(
|
828 |
+
self,
|
829 |
+
hidden_states,
|
830 |
+
attention_mask=None,
|
831 |
+
position_bias=None,
|
832 |
+
layer_head_mask=None,
|
833 |
+
past_key_value=None,
|
834 |
+
use_cache=False,
|
835 |
+
output_attentions=False,
|
836 |
+
relative_position=None,
|
837 |
+
struct_position_bias=None,
|
838 |
+
):
|
839 |
+
normed_hidden_states = self.layer_norm(hidden_states)
|
840 |
+
attention_output = self.SelfAttention(
|
841 |
+
normed_hidden_states,
|
842 |
+
mask=attention_mask,
|
843 |
+
position_bias=position_bias,
|
844 |
+
struct_position_bias=struct_position_bias,
|
845 |
+
layer_head_mask=layer_head_mask,
|
846 |
+
past_key_value=past_key_value,
|
847 |
+
use_cache=use_cache,
|
848 |
+
output_attentions=output_attentions,
|
849 |
+
relative_position=relative_position,
|
850 |
+
)
|
851 |
+
hidden_states = hidden_states + self.dropout(attention_output[0])
|
852 |
+
outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
|
853 |
+
return outputs
|
854 |
+
|
855 |
+
class CustomT5LayerCrossAttention(T5LayerCrossAttention):
|
856 |
+
def __init__(self, config, pos_enc_type="RPE", rpe_type="abs"):
|
857 |
+
super().__init__(config)
|
858 |
+
self.pos_enc_type=pos_enc_type
|
859 |
+
self.rpe_type=rpe_type
|
860 |
+
self.EncDecAttention = CustomT5Attention(config, has_relative_attention_bias=False, pos_enc_type=pos_enc_type, attn_type="cross", rpe_type=rpe_type)
|
861 |
+
self.is_decoder = config.is_decoder
|
862 |
+
|
863 |
+
def forward(
|
864 |
+
self,
|
865 |
+
hidden_states,
|
866 |
+
key_value_states,
|
867 |
+
attention_mask=None,
|
868 |
+
position_bias=None,
|
869 |
+
layer_head_mask=None,
|
870 |
+
past_key_value=None,
|
871 |
+
use_cache=False,
|
872 |
+
query_length=None,
|
873 |
+
output_attentions=False,
|
874 |
+
relative_position=None,
|
875 |
+
struct_position_bias=None,
|
876 |
+
):
|
877 |
+
normed_hidden_states = self.layer_norm(hidden_states)
|
878 |
+
attention_output = self.EncDecAttention(
|
879 |
+
normed_hidden_states,
|
880 |
+
mask=attention_mask,
|
881 |
+
key_value_states=key_value_states,
|
882 |
+
position_bias=position_bias,
|
883 |
+
layer_head_mask=layer_head_mask,
|
884 |
+
past_key_value=past_key_value,
|
885 |
+
use_cache=use_cache,
|
886 |
+
query_length=query_length,
|
887 |
+
output_attentions=output_attentions,
|
888 |
+
relative_position=relative_position,
|
889 |
+
struct_position_bias=struct_position_bias,
|
890 |
+
)
|
891 |
+
layer_output = hidden_states + self.dropout(attention_output[0])
|
892 |
+
outputs = (layer_output,) + attention_output[1:] # add attentions if we output them
|
893 |
+
return outputs
|
894 |
+
|
895 |
+
from transformers.models.t5.modeling_t5 import T5Block, T5LayerFF
|
896 |
+
|
897 |
+
class CustomT5Block(T5Block):
|
898 |
+
def __init__(self, config, has_relative_attention_bias=False, pos_enc_type="RPE", rpe_type="abs"):
|
899 |
+
super().__init__(config, has_relative_attention_bias)
|
900 |
+
self.pos_enc_type=pos_enc_type
|
901 |
+
self.rpe_type=rpe_type
|
902 |
+
self.layer = nn.ModuleList()
|
903 |
+
self.layer.append(CustomT5LayerSelfAttention(config, has_relative_attention_bias=has_relative_attention_bias, pos_enc_type=pos_enc_type, rpe_type=rpe_type))
|
904 |
+
if self.is_decoder:
|
905 |
+
self.layer.append(CustomT5LayerCrossAttention(config, pos_enc_type=pos_enc_type, rpe_type=rpe_type))
|
906 |
+
self.layer.append(T5LayerFF(config))
|
907 |
+
|
908 |
+
def forward(
|
909 |
+
self,
|
910 |
+
hidden_states,
|
911 |
+
attention_mask=None,
|
912 |
+
position_bias=None,
|
913 |
+
encoder_hidden_states=None,
|
914 |
+
encoder_attention_mask=None,
|
915 |
+
encoder_decoder_position_bias=None,
|
916 |
+
encoder_decoder_struct_position_bias=None,
|
917 |
+
layer_head_mask=None,
|
918 |
+
cross_attn_layer_head_mask=None,
|
919 |
+
past_key_value=None,
|
920 |
+
use_cache=False,
|
921 |
+
output_attentions=False,
|
922 |
+
return_dict=True,
|
923 |
+
relative_position=None,
|
924 |
+
struct_position_bias=None,
|
925 |
+
):
|
926 |
+
if past_key_value is not None:
|
927 |
+
if not self.is_decoder:
|
928 |
+
logger.warning("`past_key_values` is passed to the encoder. Please make sure this is intended.")
|
929 |
+
expected_num_past_key_values = 2 if encoder_hidden_states is None else 4
|
930 |
+
|
931 |
+
if len(past_key_value) != expected_num_past_key_values:
|
932 |
+
raise ValueError(
|
933 |
+
f"There should be {expected_num_past_key_values} past states. "
|
934 |
+
f"{'2 (key / value) for cross attention. ' if expected_num_past_key_values == 4 else ''}"
|
935 |
+
f"Got {len(past_key_value)} past key / value states"
|
936 |
+
)
|
937 |
+
|
938 |
+
self_attn_past_key_value = past_key_value[:2]
|
939 |
+
cross_attn_past_key_value = past_key_value[2:]
|
940 |
+
else:
|
941 |
+
self_attn_past_key_value, cross_attn_past_key_value = None, None
|
942 |
+
|
943 |
+
self_attention_outputs = self.layer[0](
|
944 |
+
hidden_states,
|
945 |
+
attention_mask=attention_mask,
|
946 |
+
position_bias=position_bias,
|
947 |
+
layer_head_mask=layer_head_mask,
|
948 |
+
past_key_value=self_attn_past_key_value,
|
949 |
+
use_cache=use_cache,
|
950 |
+
output_attentions=output_attentions,
|
951 |
+
relative_position=relative_position,
|
952 |
+
struct_position_bias=struct_position_bias,
|
953 |
+
)
|
954 |
+
hidden_states, present_key_value_state = self_attention_outputs[:2]
|
955 |
+
attention_outputs = self_attention_outputs[2:] # Keep self-attention outputs and relative position weights
|
956 |
+
|
957 |
+
# clamp inf values to enable fp16 training
|
958 |
+
if hidden_states.dtype == torch.float16:
|
959 |
+
clamp_value = torch.where(
|
960 |
+
torch.isinf(hidden_states).any(),
|
961 |
+
torch.finfo(hidden_states.dtype).max - 1000,
|
962 |
+
torch.finfo(hidden_states.dtype).max,
|
963 |
+
)
|
964 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
965 |
+
|
966 |
+
do_cross_attention = self.is_decoder and encoder_hidden_states is not None
|
967 |
+
if do_cross_attention:
|
968 |
+
# the actual query length is unknown for cross attention
|
969 |
+
# if using past key value states. Need to inject it here
|
970 |
+
if present_key_value_state is not None:
|
971 |
+
query_length = present_key_value_state[0].shape[2]
|
972 |
+
else:
|
973 |
+
query_length = None
|
974 |
+
|
975 |
+
cross_attention_outputs = self.layer[1](
|
976 |
+
hidden_states,
|
977 |
+
key_value_states=encoder_hidden_states,
|
978 |
+
attention_mask=encoder_attention_mask,
|
979 |
+
position_bias=encoder_decoder_position_bias,
|
980 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
981 |
+
past_key_value=cross_attn_past_key_value,
|
982 |
+
query_length=query_length,
|
983 |
+
use_cache=use_cache,
|
984 |
+
output_attentions=output_attentions,
|
985 |
+
struct_position_bias=encoder_decoder_struct_position_bias,
|
986 |
+
relative_position=relative_position,
|
987 |
+
)
|
988 |
+
hidden_states = cross_attention_outputs[0]
|
989 |
+
|
990 |
+
# clamp inf values to enable fp16 training
|
991 |
+
if hidden_states.dtype == torch.float16:
|
992 |
+
clamp_value = torch.where(
|
993 |
+
torch.isinf(hidden_states).any(),
|
994 |
+
torch.finfo(hidden_states.dtype).max - 1000,
|
995 |
+
torch.finfo(hidden_states.dtype).max,
|
996 |
+
)
|
997 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
998 |
+
|
999 |
+
# Combine self attn and cross attn key value states
|
1000 |
+
if present_key_value_state is not None:
|
1001 |
+
present_key_value_state = present_key_value_state + cross_attention_outputs[1]
|
1002 |
+
|
1003 |
+
# Keep cross-attention outputs and relative position weights
|
1004 |
+
attention_outputs = attention_outputs + cross_attention_outputs[2:]
|
1005 |
+
|
1006 |
+
# Apply Feed Forward layer
|
1007 |
+
hidden_states = self.layer[-1](hidden_states)
|
1008 |
+
|
1009 |
+
# clamp inf values to enable fp16 training
|
1010 |
+
if hidden_states.dtype == torch.float16:
|
1011 |
+
clamp_value = torch.where(
|
1012 |
+
torch.isinf(hidden_states).any(),
|
1013 |
+
torch.finfo(hidden_states.dtype).max - 1000,
|
1014 |
+
torch.finfo(hidden_states.dtype).max,
|
1015 |
+
)
|
1016 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
1017 |
+
|
1018 |
+
outputs = (hidden_states,)
|
1019 |
+
|
1020 |
+
if use_cache:
|
1021 |
+
outputs = outputs + (present_key_value_state,) + attention_outputs
|
1022 |
+
else:
|
1023 |
+
outputs = outputs + attention_outputs
|
1024 |
+
|
1025 |
+
return outputs # hidden-states, present_key_value_states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
|
1026 |
+
|
1027 |
+
|
1028 |
+
from transformers.models.t5.modeling_t5 import T5Stack
|
1029 |
+
import numpy as np
|
1030 |
+
from pathlib import Path
|
1031 |
+
import logging
|
1032 |
+
import os
|
1033 |
+
logger = logging.getLogger("debug")
|
1034 |
+
|
1035 |
+
class CustomT5Stack(T5Stack):
|
1036 |
+
def __init__(self, config, embed_tokens=None, pos_enc_type="RPE", rpe_type="abs"):
|
1037 |
+
super().__init__(config, embed_tokens)
|
1038 |
+
#self.pos_enc_type=pos_enc_type
|
1039 |
+
|
1040 |
+
# Alibi-rpe_sbias
|
1041 |
+
if "-" in pos_enc_type:
|
1042 |
+
pos_enc_split = pos_enc_type.split("-")
|
1043 |
+
self.pos_enc_type = pos_enc_split[0]
|
1044 |
+
self.struct_attn_type = pos_enc_split[1]
|
1045 |
+
else:
|
1046 |
+
self.pos_enc_type = pos_enc_type
|
1047 |
+
self.struct_attn_type = ""
|
1048 |
+
|
1049 |
+
self.rpe_type=rpe_type
|
1050 |
+
self.block = nn.ModuleList(
|
1051 |
+
[CustomT5Block(config, has_relative_attention_bias=bool(i == 0), pos_enc_type=pos_enc_type, rpe_type=rpe_type) for i in range(config.num_layers)]
|
1052 |
+
)
|
1053 |
+
|
1054 |
+
self.PE_mixer = VisionTransformerEmbedding(config.d_model, config)
|
1055 |
+
self.config = config
|
1056 |
+
|
1057 |
+
if self.pos_enc_type == "LearnedAPE":
|
1058 |
+
self.wpe = nn.Embedding(2048, config.d_model)
|
1059 |
+
self.wpe.weight.data.normal_(
|
1060 |
+
mean=0.0, std=config.initializer_factor * 1.0
|
1061 |
+
)
|
1062 |
+
|
1063 |
+
"""
|
1064 |
+
parent_dir = Path(os.path.dirname(os.path.abspath(__file__)))
|
1065 |
+
learned_embed_file = parent_dir / "gpt_neo_125m_pos_embed.npy"
|
1066 |
+
if learned_embed_file.exists():
|
1067 |
+
logger.info(
|
1068 |
+
"Loading position embedding from {}".format(learned_embed_file)
|
1069 |
+
)
|
1070 |
+
|
1071 |
+
weight = np.load(str(learned_embed_file))
|
1072 |
+
self.wpe.weight.data.copy_(torch.from_numpy(weight))
|
1073 |
+
self.wpe.weight.requires_grad = False
|
1074 |
+
else:
|
1075 |
+
self.wpe.weight.data.normal_(
|
1076 |
+
mean=0.0, std=config.initializer_factor * 1.0
|
1077 |
+
)
|
1078 |
+
"""
|
1079 |
+
|
1080 |
+
if self.pos_enc_type == "SinusoidalAPE":
|
1081 |
+
self.wpe = FixedAbsolutePositionalEmbedding(config.d_model)
|
1082 |
+
|
1083 |
+
if self.pos_enc_type in ["SinusoidalAPE2D","APEAlibi-duo","APEAlibi"]:
|
1084 |
+
# 2D APE for encoder and cross attn
|
1085 |
+
# A norminate obj_id just to test
|
1086 |
+
if config.use_objidx=="yes":
|
1087 |
+
self.wpe_obj_enc = FixedAbsolutePositionalEmbedding(config.d_model/2) # 128/2 -> 64
|
1088 |
+
self.wpe_x_enc = FixedAbsolutePositionalEmbedding(config.d_model/4) # 128/4 -> 32
|
1089 |
+
self.wpe_y_enc = FixedAbsolutePositionalEmbedding(config.d_model/4) # 128/4 -> 32
|
1090 |
+
|
1091 |
+
# Decoder is the same old 2D
|
1092 |
+
self.wpe_x = FixedAbsolutePositionalEmbedding(config.d_model/2) # 128/2 -> 64
|
1093 |
+
self.wpe_y = FixedAbsolutePositionalEmbedding(config.d_model/2) # 128/2 -> 64
|
1094 |
+
|
1095 |
+
# 1D APE for decoder/ non-2d positions
|
1096 |
+
self.wpe = FixedAbsolutePositionalEmbedding(config.d_model)
|
1097 |
+
|
1098 |
+
if self.pos_enc_type in ["Alibi-duo", "Alibi", "APEAlibi-duo", "APEAlibi"]:
|
1099 |
+
# Calculate relative positions for the 2D grid
|
1100 |
+
grid_height = self.config.grid_max_height
|
1101 |
+
grid_width = self.config.grid_max_width
|
1102 |
+
large_dist = max(grid_height,grid_width)+2
|
1103 |
+
relative_position_2d = self.calculate_2d_relative_positions(grid_height, grid_width)
|
1104 |
+
|
1105 |
+
# Create a relative position matrix for the full sequence including <s> and </s>
|
1106 |
+
total_length = grid_height * grid_width + 2 # +2 for <s> and </s>
|
1107 |
+
distance_matrix = torch.full((total_length, total_length), fill_value=large_dist) # 100 as a large distance
|
1108 |
+
|
1109 |
+
# Assign the 2D relative positions to the correct part of the matrix
|
1110 |
+
distance_matrix[1:1 + grid_height * grid_width, 1:1 + grid_height * grid_width] = relative_position_2d
|
1111 |
+
|
1112 |
+
# Optionally handle <s> and </s> relative positions
|
1113 |
+
distance_matrix[0, :] = large_dist # <s> is far from everything
|
1114 |
+
distance_matrix[:, 0] = large_dist
|
1115 |
+
distance_matrix[-1, :] = large_dist+1 # </s> is far from everything
|
1116 |
+
distance_matrix[:, -1] = large_dist+1
|
1117 |
+
|
1118 |
+
self.distance_matrix_2D = distance_matrix
|
1119 |
+
#self.register_buffer("distance_matrix", self.distance_matrix)
|
1120 |
+
|
1121 |
+
def calculate_2d_relative_positions(self, grid_height, grid_width):
|
1122 |
+
# Create grid coordinates
|
1123 |
+
x_coords, y_coords = torch.meshgrid(
|
1124 |
+
torch.arange(grid_height, dtype=torch.long),
|
1125 |
+
torch.arange(grid_width, dtype=torch.long),
|
1126 |
+
indexing='ij'
|
1127 |
+
)
|
1128 |
+
|
1129 |
+
# Flatten the 2D grid coordinates
|
1130 |
+
x_flat = x_coords.flatten()
|
1131 |
+
y_flat = y_coords.flatten()
|
1132 |
+
|
1133 |
+
# Initialize the relative position matrix
|
1134 |
+
num_positions = grid_height * grid_width
|
1135 |
+
relative_position = torch.zeros((num_positions, num_positions), dtype=torch.long)
|
1136 |
+
|
1137 |
+
# Calculate Manhattan distance between each pair of points
|
1138 |
+
for i in range(num_positions):
|
1139 |
+
for j in range(num_positions):
|
1140 |
+
relative_position[i, j] = abs(x_flat[i] - x_flat[j]) + abs(y_flat[i] - y_flat[j])
|
1141 |
+
|
1142 |
+
return relative_position
|
1143 |
+
|
1144 |
+
|
1145 |
+
def forward(
|
1146 |
+
self,
|
1147 |
+
input_ids=None,
|
1148 |
+
attention_mask=None,
|
1149 |
+
encoder_hidden_states=None,
|
1150 |
+
encoder_attention_mask=None,
|
1151 |
+
inputs_embeds=None,
|
1152 |
+
head_mask=None,
|
1153 |
+
cross_attn_head_mask=None,
|
1154 |
+
past_key_values=None,
|
1155 |
+
use_cache=None,
|
1156 |
+
output_attentions=None,
|
1157 |
+
output_hidden_states=None,
|
1158 |
+
position_ids=None,
|
1159 |
+
return_dict=None,
|
1160 |
+
relative_position=None,
|
1161 |
+
object_idx=None,
|
1162 |
+
):
|
1163 |
+
# Model parallel
|
1164 |
+
if self.model_parallel:
|
1165 |
+
torch.cuda.set_device(self.first_device)
|
1166 |
+
self.embed_tokens = self.embed_tokens.to(self.first_device)
|
1167 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1168 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1169 |
+
output_hidden_states = (
|
1170 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1171 |
+
)
|
1172 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1173 |
+
|
1174 |
+
if input_ids is not None and inputs_embeds is not None:
|
1175 |
+
err_msg_prefix = "decoder_" if self.is_decoder else ""
|
1176 |
+
raise ValueError(
|
1177 |
+
f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
|
1178 |
+
)
|
1179 |
+
elif input_ids is not None:
|
1180 |
+
input_shape = input_ids.size()
|
1181 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
1182 |
+
elif inputs_embeds is not None:
|
1183 |
+
input_shape = inputs_embeds.size()[:-1]
|
1184 |
+
else:
|
1185 |
+
err_msg_prefix = "decoder_" if self.is_decoder else ""
|
1186 |
+
raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
|
1187 |
+
|
1188 |
+
if self.pos_enc_type in ["Alibi-duo", "Alibi", "APEAlibi-duo", "APEAlibi"]:
|
1189 |
+
relative_position = self.distance_matrix_2D
|
1190 |
+
|
1191 |
+
#print(f"input_ids.shape:{input_ids.shape}")
|
1192 |
+
# Print the shape of the embedding matrix
|
1193 |
+
#print(f"Embedding matrix shape: {self.embed_tokens.weight.shape}")
|
1194 |
+
# Print unique values in input_ids
|
1195 |
+
#unique_input_ids = torch.unique(input_ids)
|
1196 |
+
#print(f"Unique input IDs: {unique_input_ids}")
|
1197 |
+
#print(f"Max input ID: {torch.max(unique_input_ids)}")
|
1198 |
+
#print(f"Min input ID: {torch.min(unique_input_ids)}")
|
1199 |
+
|
1200 |
+
if inputs_embeds is None:
|
1201 |
+
if self.embed_tokens is None:
|
1202 |
+
raise ValueError("You have to initialize the model with valid token embeddings")
|
1203 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
1204 |
+
|
1205 |
+
#print(f"inputs_embeds.shape:{inputs_embeds.shape}")
|
1206 |
+
|
1207 |
+
batch_size, seq_length = input_shape
|
1208 |
+
|
1209 |
+
# required mask seq length can be calculated via length of past
|
1210 |
+
mask_seq_length = past_key_values[0][0].shape[2] + seq_length if past_key_values is not None else seq_length
|
1211 |
+
#print(f"mask_seq_length:{mask_seq_length}")
|
1212 |
+
|
1213 |
+
|
1214 |
+
# Add 2D position embeddings, but only on input seq
|
1215 |
+
if self.pos_enc_type in [
|
1216 |
+
"SinusoidalAPE2D","APEAlibi-duo","APEAlibi"
|
1217 |
+
]:
|
1218 |
+
if self.is_decoder or self.config.use_objidx!="yes":
|
1219 |
+
if position_ids is not None:
|
1220 |
+
position_ids = position_ids.view(-1, input_shape[-1])
|
1221 |
+
|
1222 |
+
if past_key_values is None:
|
1223 |
+
past_length = 0
|
1224 |
+
else:
|
1225 |
+
past_length = past_key_values[0][0].size(-2)
|
1226 |
+
|
1227 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1228 |
+
if position_ids is None:
|
1229 |
+
position_ids = torch.arange(
|
1230 |
+
past_length,
|
1231 |
+
input_shape[-1] + past_length,
|
1232 |
+
dtype=torch.long,
|
1233 |
+
device=device,
|
1234 |
+
)
|
1235 |
+
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
|
1236 |
+
|
1237 |
+
#print(f"position_ids.shape:{position_ids.shape}")
|
1238 |
+
#print(f"position_ids:{position_ids}")
|
1239 |
+
|
1240 |
+
if position_ids.shape[-1] == 1024 or position_ids.shape[-1] == 1025 or True:
|
1241 |
+
#if position_ids.shape[-1] == 1024 or position_ids.shape[-1] == 1025:
|
1242 |
+
# Desired dimensions for ARC IO, individually
|
1243 |
+
# For decoder because we have <pad> as first token
|
1244 |
+
rows = self.config.grid_max_height
|
1245 |
+
cols = self.config.grid_max_width
|
1246 |
+
|
1247 |
+
# Flatten the position_ids tensor to remove batch dimension
|
1248 |
+
flat_position_ids = position_ids.view(-1)
|
1249 |
+
#print(f"flat_position_ids.shape:{flat_position_ids.shape}")
|
1250 |
+
#print(f"flat_position_ids:{flat_position_ids}")
|
1251 |
+
|
1252 |
+
# Generate position_ids_x
|
1253 |
+
position_ids_x = torch.arange(cols, device=device).repeat(rows)
|
1254 |
+
|
1255 |
+
# Generate position_ids_y
|
1256 |
+
position_ids_y = torch.arange(rows, device=device).repeat_interleave(cols)
|
1257 |
+
|
1258 |
+
# Handling batch size, repeat for each batch
|
1259 |
+
batch_size = position_ids.shape[0]
|
1260 |
+
position_ids_x = position_ids_x.repeat(batch_size, 1)
|
1261 |
+
position_ids_y = position_ids_y.repeat(batch_size, 1)
|
1262 |
+
|
1263 |
+
#position_embeds = self.wpe(position_ids)
|
1264 |
+
position_embeds_x = self.wpe_x(position_ids_x)
|
1265 |
+
position_embeds_y = self.wpe_y(position_ids_y)
|
1266 |
+
#print(f"position_embeds_x.shape:{position_embeds_x.shape}")
|
1267 |
+
|
1268 |
+
#position_embeds
|
1269 |
+
position_embeds_2d = torch.cat((position_embeds_x, position_embeds_y), dim=-1)
|
1270 |
+
# Apply 1D sinAPE for the <pad> token and tokens beyond 2+1024
|
1271 |
+
position_embeds_1d = self.wpe(position_ids)
|
1272 |
+
if self.is_decoder:
|
1273 |
+
# Combine embeddings
|
1274 |
+
position_embeds = position_embeds_1d.clone()
|
1275 |
+
#print(f"position_embeds=position_embeds_1d.clone().shape:{position_embeds.shape}")
|
1276 |
+
|
1277 |
+
p_seq_len = position_ids.shape[-1]
|
1278 |
+
#print(f"p_seq_len:{p_seq_len}")
|
1279 |
+
if p_seq_len >= 1123:
|
1280 |
+
position_embeds[:, 1:1123] = position_embeds_2d[:, :1122]
|
1281 |
+
elif p_seq_len == 1:
|
1282 |
+
pos_index = flat_position_ids[0]
|
1283 |
+
if pos_index == 0:
|
1284 |
+
# <pad> for 1d APE
|
1285 |
+
pass
|
1286 |
+
elif pos_index>1 and pos_index<=1122:
|
1287 |
+
# For model.generate() this will always be 1, but position_ids=(bs, pos_index)
|
1288 |
+
position_embeds[:, 0] = position_embeds_2d[:, pos_index-1]
|
1289 |
+
else:
|
1290 |
+
# > 1025
|
1291 |
+
pass
|
1292 |
+
else:
|
1293 |
+
#print(f"position_embeds.shape:{position_embeds.shape}")
|
1294 |
+
#print(f"position_embeds_2d.shape:{position_embeds_2d.shape}")
|
1295 |
+
#print(f"position_embeds[:, 1:p_seq_len].shape:{position_embeds[:, 1:p_seq_len].shape}")
|
1296 |
+
#print(f"position_embeds_2d[:, :p_seq_len-1].shape:{position_embeds_2d[:, :p_seq_len-1].shape}")
|
1297 |
+
position_embeds[:, 1:p_seq_len] = position_embeds_2d[:, :p_seq_len-1]
|
1298 |
+
else:
|
1299 |
+
position_embeds = position_embeds_1d.clone()
|
1300 |
+
position_embeds[:, 1:1123] = position_embeds_2d[:, :1122]
|
1301 |
+
else:
|
1302 |
+
# 1D sinAPE
|
1303 |
+
position_embeds = self.wpe(position_ids)
|
1304 |
+
else:
|
1305 |
+
# if NOT self.is_decoder:
|
1306 |
+
if position_ids is not None:
|
1307 |
+
position_ids = position_ids.view(-1, input_shape[-1])
|
1308 |
+
|
1309 |
+
if past_key_values is None:
|
1310 |
+
past_length = 0
|
1311 |
+
else:
|
1312 |
+
past_length = past_key_values[0][0].size(-2)
|
1313 |
+
|
1314 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1315 |
+
if position_ids is None:
|
1316 |
+
position_ids = torch.arange(
|
1317 |
+
past_length,
|
1318 |
+
input_shape[-1] + past_length,
|
1319 |
+
dtype=torch.long,
|
1320 |
+
device=device,
|
1321 |
+
)
|
1322 |
+
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
|
1323 |
+
|
1324 |
+
#print(f"position_ids.shape:{position_ids.shape}")
|
1325 |
+
#print(f"position_ids:{position_ids}")
|
1326 |
+
|
1327 |
+
if position_ids.shape[-1] == 1024 or position_ids.shape[-1] == 1025 or True:
|
1328 |
+
#if position_ids.shape[-1] == 1024 or position_ids.shape[-1] == 1025:
|
1329 |
+
# Desired dimensions for ARC IO, individually
|
1330 |
+
# For decoder because we have <pad> as first token
|
1331 |
+
rows = self.config.grid_max_height
|
1332 |
+
cols = self.config.grid_max_width
|
1333 |
+
|
1334 |
+
# Flatten the position_ids tensor to remove batch dimension
|
1335 |
+
flat_position_ids = position_ids.view(-1)
|
1336 |
+
#print(f"flat_position_ids.shape:{flat_position_ids.shape}")
|
1337 |
+
#print(f"flat_position_ids:{flat_position_ids}")
|
1338 |
+
|
1339 |
+
# Generate position_ids_x
|
1340 |
+
position_ids_x = torch.arange(cols, device=device).repeat(rows)
|
1341 |
+
|
1342 |
+
# Generate position_ids_y
|
1343 |
+
position_ids_y = torch.arange(rows, device=device).repeat_interleave(cols)
|
1344 |
+
|
1345 |
+
# Handling batch size, repeat for each batch
|
1346 |
+
batch_size = position_ids.shape[0]
|
1347 |
+
position_ids_x = position_ids_x.repeat(batch_size, 1)
|
1348 |
+
position_ids_y = position_ids_y.repeat(batch_size, 1)
|
1349 |
+
|
1350 |
+
# Get the object embeddings
|
1351 |
+
object_embeds = self.wpe_obj_enc(object_idx[:, 1:-1]) # Assuming `object_idx` is passed in
|
1352 |
+
#print(f"object_idx.shape:{object_idx.shape}")
|
1353 |
+
#print(f"object_embeds.shape:{object_embeds.shape}")
|
1354 |
+
|
1355 |
+
#position_embeds = self.wpe(position_ids)
|
1356 |
+
position_embeds_x = self.wpe_x_enc(position_ids_x)
|
1357 |
+
#print(f"position_ids_x.shape:{position_ids_x.shape}")
|
1358 |
+
#print(f"position_embeds_x.shape:{position_embeds_x.shape}")
|
1359 |
+
position_embeds_y = self.wpe_y_enc(position_ids_y)
|
1360 |
+
|
1361 |
+
# Expand position_embeds_x and position_embeds_y to match the batch size
|
1362 |
+
position_embeds_x = position_embeds_x.expand(object_embeds.size(0), -1, -1) # Expand along the batch size
|
1363 |
+
position_embeds_y = position_embeds_y.expand(object_embeds.size(0), -1, -1) # Expand along the batch size
|
1364 |
+
|
1365 |
+
#position_embeds
|
1366 |
+
#position_embeds_2d = torch.cat((position_embeds_x, position_embeds_y), dim=-1)
|
1367 |
+
position_embeds_2d = torch.cat((object_embeds, position_embeds_x, position_embeds_y), dim=-1)
|
1368 |
+
|
1369 |
+
# Apply 1D sinAPE for the <pad> token and tokens beyond 2+1024
|
1370 |
+
position_embeds_1d = self.wpe(position_ids)
|
1371 |
+
position_embeds_1d = position_embeds_1d.expand(object_embeds.size(0), -1, -1) # Expand along the batch size
|
1372 |
+
|
1373 |
+
position_embeds = position_embeds_1d.clone()
|
1374 |
+
position_embeds[:, 1:1123] = position_embeds_2d[:, :1122]
|
1375 |
+
else:
|
1376 |
+
# 1D sinAPE
|
1377 |
+
position_embeds = self.wpe(position_ids)
|
1378 |
+
|
1379 |
+
#print(f"position_embeds.shape:{position_embeds.shape}")
|
1380 |
+
#print(f"position_embeds:{position_embeds}")
|
1381 |
+
#inputs_embeds += position_embeds
|
1382 |
+
inputs_embeds = self.PE_mixer(inputs_embeds, position_embeds)
|
1383 |
+
|
1384 |
+
if self.pos_enc_type in [
|
1385 |
+
"SinusoidalAPE",
|
1386 |
+
"LearnedAPE",
|
1387 |
+
]:
|
1388 |
+
if position_ids is not None:
|
1389 |
+
position_ids = position_ids.view(-1, input_shape[-1])
|
1390 |
+
|
1391 |
+
if past_key_values is None:
|
1392 |
+
past_length = 0
|
1393 |
+
else:
|
1394 |
+
past_length = past_key_values[0][0].size(-2)
|
1395 |
+
|
1396 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1397 |
+
if position_ids is None:
|
1398 |
+
position_ids = torch.arange(
|
1399 |
+
past_length,
|
1400 |
+
input_shape[-1] + past_length,
|
1401 |
+
dtype=torch.long,
|
1402 |
+
device=device,
|
1403 |
+
)
|
1404 |
+
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
|
1405 |
+
|
1406 |
+
#print(f"position_ids.shape:{position_ids.shape}")
|
1407 |
+
position_embeds = self.wpe(position_ids)
|
1408 |
+
#print(f"position_embeds.shape:{position_embeds.shape}")
|
1409 |
+
inputs_embeds += position_embeds
|
1410 |
+
|
1411 |
+
if self.struct_attn_type == "ape_sbias":
|
1412 |
+
# Extra APE, naive trial
|
1413 |
+
if relative_position is not None:
|
1414 |
+
struct_position_ids = relative_position.view(-1, input_shape[-1])
|
1415 |
+
#print(relative_position)
|
1416 |
+
#print(f"struct_position_ids.shape:{struct_position_ids.shape}")
|
1417 |
+
#print(struct_position_ids)
|
1418 |
+
struct_position_embeds = self.wpe(struct_position_ids)
|
1419 |
+
#print(f"struct_position_embeds.shape:{struct_position_embeds.shape}")
|
1420 |
+
inputs_embeds += struct_position_embeds
|
1421 |
+
|
1422 |
+
if use_cache is True:
|
1423 |
+
if not self.is_decoder:
|
1424 |
+
raise ValueError(f"`use_cache` can only be set to `True` if {self} is used as a decoder")
|
1425 |
+
|
1426 |
+
# initialize past_key_values with `None` if past does not exist
|
1427 |
+
if past_key_values is None:
|
1428 |
+
past_key_values = [None] * len(self.block)
|
1429 |
+
|
1430 |
+
if attention_mask is None:
|
1431 |
+
attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
|
1432 |
+
|
1433 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
1434 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
1435 |
+
extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
|
1436 |
+
|
1437 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
1438 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
1439 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
1440 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
1441 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
1442 |
+
if encoder_attention_mask is None:
|
1443 |
+
encoder_attention_mask = torch.ones(
|
1444 |
+
encoder_hidden_shape, device=inputs_embeds.device, dtype=torch.long
|
1445 |
+
)
|
1446 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
1447 |
+
else:
|
1448 |
+
encoder_extended_attention_mask = None
|
1449 |
+
|
1450 |
+
if self.gradient_checkpointing and self.training:
|
1451 |
+
if use_cache:
|
1452 |
+
logger.warning_once(
|
1453 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
1454 |
+
)
|
1455 |
+
use_cache = False
|
1456 |
+
|
1457 |
+
# Prepare head mask if needed
|
1458 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_layers)
|
1459 |
+
cross_attn_head_mask = self.get_head_mask(cross_attn_head_mask, self.config.num_layers)
|
1460 |
+
present_key_value_states = () if use_cache else None
|
1461 |
+
all_hidden_states = () if output_hidden_states else None
|
1462 |
+
all_attentions = () if output_attentions else None
|
1463 |
+
all_cross_attentions = () if (output_attentions and self.is_decoder) else None
|
1464 |
+
position_bias = None
|
1465 |
+
struct_position_bias = None
|
1466 |
+
encoder_decoder_position_bias = None
|
1467 |
+
encoder_decoder_struct_position_bias = None
|
1468 |
+
|
1469 |
+
hidden_states = self.dropout(inputs_embeds)
|
1470 |
+
|
1471 |
+
for i, (layer_module, past_key_value) in enumerate(zip(self.block, past_key_values)):
|
1472 |
+
layer_head_mask = head_mask[i]
|
1473 |
+
cross_attn_layer_head_mask = cross_attn_head_mask[i]
|
1474 |
+
# Model parallel
|
1475 |
+
if self.model_parallel:
|
1476 |
+
torch.cuda.set_device(hidden_states.device)
|
1477 |
+
# Ensure that attention_mask is always on the same device as hidden_states
|
1478 |
+
if attention_mask is not None:
|
1479 |
+
attention_mask = attention_mask.to(hidden_states.device)
|
1480 |
+
if position_bias is not None:
|
1481 |
+
position_bias = position_bias.to(hidden_states.device)
|
1482 |
+
if struct_position_bias is not None:
|
1483 |
+
struct_position_bias = struct_position_bias.to(hidden_states.device)
|
1484 |
+
if encoder_hidden_states is not None:
|
1485 |
+
encoder_hidden_states = encoder_hidden_states.to(hidden_states.device)
|
1486 |
+
if encoder_extended_attention_mask is not None:
|
1487 |
+
encoder_extended_attention_mask = encoder_extended_attention_mask.to(hidden_states.device)
|
1488 |
+
if encoder_decoder_position_bias is not None:
|
1489 |
+
encoder_decoder_position_bias = encoder_decoder_position_bias.to(hidden_states.device)
|
1490 |
+
if encoder_decoder_struct_position_bias is not None:
|
1491 |
+
encoder_decoder_struct_position_bias = encoder_decoder_struct_position_bias.to(hidden_states.device)
|
1492 |
+
if layer_head_mask is not None:
|
1493 |
+
layer_head_mask = layer_head_mask.to(hidden_states.device)
|
1494 |
+
if cross_attn_layer_head_mask is not None:
|
1495 |
+
cross_attn_layer_head_mask = cross_attn_layer_head_mask.to(hidden_states.device)
|
1496 |
+
if output_hidden_states:
|
1497 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
1498 |
+
|
1499 |
+
if self.gradient_checkpointing and self.training:
|
1500 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1501 |
+
layer_module.forward,
|
1502 |
+
hidden_states,
|
1503 |
+
extended_attention_mask,
|
1504 |
+
position_bias,
|
1505 |
+
encoder_hidden_states,
|
1506 |
+
encoder_extended_attention_mask,
|
1507 |
+
encoder_decoder_position_bias,
|
1508 |
+
layer_head_mask,
|
1509 |
+
cross_attn_layer_head_mask,
|
1510 |
+
None, # past_key_value is always None with gradient checkpointing
|
1511 |
+
use_cache,
|
1512 |
+
output_attentions,
|
1513 |
+
)
|
1514 |
+
else:
|
1515 |
+
layer_outputs = layer_module(
|
1516 |
+
hidden_states,
|
1517 |
+
attention_mask=extended_attention_mask,
|
1518 |
+
position_bias=position_bias,
|
1519 |
+
struct_position_bias=struct_position_bias, # Pass the struct_position_bias to the layer
|
1520 |
+
encoder_hidden_states=encoder_hidden_states,
|
1521 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
1522 |
+
encoder_decoder_position_bias=encoder_decoder_position_bias,
|
1523 |
+
encoder_decoder_struct_position_bias=encoder_decoder_struct_position_bias,
|
1524 |
+
layer_head_mask=layer_head_mask,
|
1525 |
+
cross_attn_layer_head_mask=cross_attn_layer_head_mask,
|
1526 |
+
past_key_value=past_key_value,
|
1527 |
+
use_cache=use_cache,
|
1528 |
+
output_attentions=output_attentions,
|
1529 |
+
relative_position=relative_position, # Pass the relative_position to the layer
|
1530 |
+
)
|
1531 |
+
|
1532 |
+
# layer_outputs is a tuple with:
|
1533 |
+
# hidden-states, key-value-states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
|
1534 |
+
# hidden-states, key-value-states, (self-attention position bias), (self-attention struct position bias), (self-attention weights),
|
1535 |
+
# (cross-attention position bias), (cross-attention struct position bias), (cross-attention weights)
|
1536 |
+
if use_cache is False:
|
1537 |
+
layer_outputs = layer_outputs[:1] + (None,) + layer_outputs[1:]
|
1538 |
+
|
1539 |
+
hidden_states, present_key_value_state = layer_outputs[:2]
|
1540 |
+
|
1541 |
+
# We share the position biases between the layers - the first layer store them
|
1542 |
+
# layer_outputs = hidden-states, key-value-states (self-attention position bias), (self-attention weights),
|
1543 |
+
# (cross-attention position bias), (cross-attention weights)
|
1544 |
+
position_bias = layer_outputs[2]
|
1545 |
+
struct_position_bias = layer_outputs[3]
|
1546 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
1547 |
+
encoder_decoder_position_bias = layer_outputs[5 if output_attentions else 4]
|
1548 |
+
encoder_decoder_struct_position_bias = layer_outputs[7 if output_attentions else 5]
|
1549 |
+
|
1550 |
+
# append next layer key value states
|
1551 |
+
if use_cache:
|
1552 |
+
present_key_value_states = present_key_value_states + (present_key_value_state,)
|
1553 |
+
|
1554 |
+
"""
|
1555 |
+
if output_attentions:
|
1556 |
+
all_attentions = all_attentions + (layer_outputs[3],)
|
1557 |
+
if self.is_decoder:
|
1558 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[5],)
|
1559 |
+
"""
|
1560 |
+
|
1561 |
+
if output_attentions:
|
1562 |
+
all_attentions = all_attentions + (layer_outputs[4],)
|
1563 |
+
if self.is_decoder:
|
1564 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[6],)
|
1565 |
+
|
1566 |
+
# Model Parallel: If it's the last layer for that device, put things on the next device
|
1567 |
+
if self.model_parallel:
|
1568 |
+
for k, v in self.device_map.items():
|
1569 |
+
if i == v[-1] and "cuda:" + str(k) != self.last_device:
|
1570 |
+
hidden_states = hidden_states.to("cuda:" + str(k + 1))
|
1571 |
+
|
1572 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
1573 |
+
hidden_states = self.dropout(hidden_states)
|
1574 |
+
|
1575 |
+
# Add last layer
|
1576 |
+
if output_hidden_states:
|
1577 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
1578 |
+
|
1579 |
+
if not return_dict:
|
1580 |
+
return tuple(
|
1581 |
+
v
|
1582 |
+
for v in [
|
1583 |
+
hidden_states,
|
1584 |
+
present_key_value_states,
|
1585 |
+
all_hidden_states,
|
1586 |
+
all_attentions,
|
1587 |
+
all_cross_attentions,
|
1588 |
+
]
|
1589 |
+
if v is not None
|
1590 |
+
)
|
1591 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
1592 |
+
last_hidden_state=hidden_states,
|
1593 |
+
past_key_values=present_key_value_states,
|
1594 |
+
hidden_states=all_hidden_states,
|
1595 |
+
attentions=all_attentions,
|
1596 |
+
cross_attentions=all_cross_attentions,
|
1597 |
+
)
|
1598 |
+
|
1599 |
+
|
1600 |
+
from transformers.models.t5.modeling_t5 import T5ForConditionalGeneration, T5Config
|
1601 |
+
|
1602 |
+
import copy
|
1603 |
+
import math
|
1604 |
+
import os
|
1605 |
+
import warnings
|
1606 |
+
from typing import List, Optional, Tuple, Union
|
1607 |
+
|
1608 |
+
import torch
|
1609 |
+
from torch import nn
|
1610 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
1611 |
+
|
1612 |
+
from transformers.activations import ACT2FN
|
1613 |
+
from transformers.modeling_outputs import (
|
1614 |
+
BaseModelOutput,
|
1615 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
1616 |
+
Seq2SeqLMOutput,
|
1617 |
+
Seq2SeqModelOutput,
|
1618 |
+
Seq2SeqQuestionAnsweringModelOutput,
|
1619 |
+
Seq2SeqSequenceClassifierOutput,
|
1620 |
+
TokenClassifierOutput,
|
1621 |
+
)
|
1622 |
+
from transformers.modeling_utils import PreTrainedModel
|
1623 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, find_pruneable_heads_and_indices, prune_linear_layer
|
1624 |
+
from transformers.utils import (
|
1625 |
+
DUMMY_INPUTS,
|
1626 |
+
DUMMY_MASK,
|
1627 |
+
add_start_docstrings,
|
1628 |
+
add_start_docstrings_to_model_forward,
|
1629 |
+
is_torch_fx_proxy,
|
1630 |
+
logging,
|
1631 |
+
replace_return_docstrings,
|
1632 |
+
)
|
1633 |
+
from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
|
1634 |
+
from transformers.models.t5.configuration_t5 import T5Config
|
1635 |
+
|
1636 |
+
# Warning message for FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
|
1637 |
+
__HEAD_MASK_WARNING_MSG = """
|
1638 |
+
The input argument `head_mask` was split into two arguments `head_mask` and `decoder_head_mask`. Currently,
|
1639 |
+
`decoder_head_mask` is set to copy `head_mask`, but this feature is deprecated and will be removed in future versions.
|
1640 |
+
If you do not want to use any `decoder_head_mask` now, please set `decoder_head_mask = torch.ones(num_layers,
|
1641 |
+
num_heads)`.
|
1642 |
+
"""
|
1643 |
+
|
1644 |
+
class CustomT5ForConditionalGeneration(T5ForConditionalGeneration):
|
1645 |
+
def __init__(self, config: T5Config, pos_enc_type="RPE", rpe_type="abs"):
|
1646 |
+
super().__init__(config)
|
1647 |
+
self.model_dim = config.d_model
|
1648 |
+
self.pos_enc_type=pos_enc_type
|
1649 |
+
self.rpe_type=rpe_type
|
1650 |
+
|
1651 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
1652 |
+
|
1653 |
+
encoder_config = copy.deepcopy(config)
|
1654 |
+
encoder_config.is_decoder = False
|
1655 |
+
encoder_config.use_cache = False
|
1656 |
+
encoder_config.is_encoder_decoder = False
|
1657 |
+
self.encoder = CustomT5Stack(encoder_config, self.shared, pos_enc_type=pos_enc_type, rpe_type=rpe_type)
|
1658 |
+
|
1659 |
+
decoder_config = copy.deepcopy(config)
|
1660 |
+
decoder_config.is_decoder = True
|
1661 |
+
decoder_config.is_encoder_decoder = False
|
1662 |
+
decoder_config.num_layers = config.num_decoder_layers
|
1663 |
+
self.decoder = CustomT5Stack(decoder_config, self.shared, pos_enc_type=pos_enc_type, rpe_type=rpe_type)
|
1664 |
+
|
1665 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
1666 |
+
|
1667 |
+
# Initialize weights and apply final processing
|
1668 |
+
self.post_init()
|
1669 |
+
|
1670 |
+
# Model parallel
|
1671 |
+
self.model_parallel = False
|
1672 |
+
self.device_map = None
|
1673 |
+
|
1674 |
+
def forward(
|
1675 |
+
self,
|
1676 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1677 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1678 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
1679 |
+
decoder_attention_mask: Optional[torch.BoolTensor] = None,
|
1680 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1681 |
+
decoder_head_mask: Optional[torch.FloatTensor] = None,
|
1682 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
1683 |
+
encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
1684 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
1685 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1686 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
1687 |
+
labels: Optional[torch.LongTensor] = None,
|
1688 |
+
use_cache: Optional[bool] = None,
|
1689 |
+
output_attentions: Optional[bool] = None,
|
1690 |
+
output_hidden_states: Optional[bool] = None,
|
1691 |
+
return_dict: Optional[bool] = None,
|
1692 |
+
# customized distance_matrix w.r.t to encoder self-attention
|
1693 |
+
distance_matrix: Optional[torch.FloatTensor] = None,
|
1694 |
+
object_idx: Optional[torch.FloatTensor] = None,
|
1695 |
+
# unlike nlp [0,..n] natural sequence, customized struct_position_indexs
|
1696 |
+
# For now, just re-use distance_matrix if APE-sbias
|
1697 |
+
#struct_position_indexs: Optional[torch.FloatTensor] = None,
|
1698 |
+
) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:
|
1699 |
+
r"""
|
1700 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1701 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
|
1702 |
+
config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
|
1703 |
+
labels in `[0, ..., config.vocab_size]`
|
1704 |
+
|
1705 |
+
Returns:
|
1706 |
+
|
1707 |
+
Examples:
|
1708 |
+
|
1709 |
+
```python
|
1710 |
+
>>> from transformers import AutoTokenizer, T5ForConditionalGeneration
|
1711 |
+
|
1712 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
|
1713 |
+
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")
|
1714 |
+
|
1715 |
+
>>> # training
|
1716 |
+
>>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
|
1717 |
+
>>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids
|
1718 |
+
>>> outputs = model(input_ids=input_ids, labels=labels)
|
1719 |
+
>>> loss = outputs.loss
|
1720 |
+
>>> logits = outputs.logits
|
1721 |
+
|
1722 |
+
>>> # inference
|
1723 |
+
>>> input_ids = tokenizer(
|
1724 |
+
... "summarize: studies have shown that owning a dog is good for you", return_tensors="pt"
|
1725 |
+
... ).input_ids # Batch size 1
|
1726 |
+
>>> outputs = model.generate(input_ids)
|
1727 |
+
>>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
1728 |
+
>>> # studies have shown that owning a dog is good for you.
|
1729 |
+
```"""
|
1730 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1731 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1732 |
+
|
1733 |
+
# FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
|
1734 |
+
if head_mask is not None and decoder_head_mask is None:
|
1735 |
+
if self.config.num_layers == self.config.num_decoder_layers:
|
1736 |
+
warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)
|
1737 |
+
decoder_head_mask = head_mask
|
1738 |
+
|
1739 |
+
# Encode if needed (training, first prediction pass)
|
1740 |
+
if encoder_outputs is None:
|
1741 |
+
# Convert encoder inputs in embeddings if needed
|
1742 |
+
encoder_outputs = self.encoder(
|
1743 |
+
input_ids=input_ids,
|
1744 |
+
attention_mask=attention_mask,
|
1745 |
+
inputs_embeds=inputs_embeds,
|
1746 |
+
head_mask=head_mask,
|
1747 |
+
output_attentions=output_attentions,
|
1748 |
+
output_hidden_states=output_hidden_states,
|
1749 |
+
return_dict=return_dict,
|
1750 |
+
relative_position=distance_matrix, # Pass the distance_matrix here
|
1751 |
+
object_idx=object_idx,
|
1752 |
+
)
|
1753 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
1754 |
+
encoder_outputs = BaseModelOutput(
|
1755 |
+
last_hidden_state=encoder_outputs[0],
|
1756 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
1757 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
1758 |
+
)
|
1759 |
+
|
1760 |
+
hidden_states = encoder_outputs[0]
|
1761 |
+
|
1762 |
+
if self.model_parallel:
|
1763 |
+
torch.cuda.set_device(self.decoder.first_device)
|
1764 |
+
|
1765 |
+
if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
|
1766 |
+
# get decoder inputs from shifting lm labels to the right
|
1767 |
+
decoder_input_ids = self._shift_right(labels)
|
1768 |
+
|
1769 |
+
# Set device for model parallelism
|
1770 |
+
if self.model_parallel:
|
1771 |
+
torch.cuda.set_device(self.decoder.first_device)
|
1772 |
+
hidden_states = hidden_states.to(self.decoder.first_device)
|
1773 |
+
if decoder_input_ids is not None:
|
1774 |
+
decoder_input_ids = decoder_input_ids.to(self.decoder.first_device)
|
1775 |
+
if attention_mask is not None:
|
1776 |
+
attention_mask = attention_mask.to(self.decoder.first_device)
|
1777 |
+
if decoder_attention_mask is not None:
|
1778 |
+
decoder_attention_mask = decoder_attention_mask.to(self.decoder.first_device)
|
1779 |
+
|
1780 |
+
# Decode
|
1781 |
+
decoder_outputs = self.decoder(
|
1782 |
+
input_ids=decoder_input_ids,
|
1783 |
+
attention_mask=decoder_attention_mask,
|
1784 |
+
inputs_embeds=decoder_inputs_embeds,
|
1785 |
+
past_key_values=past_key_values,
|
1786 |
+
encoder_hidden_states=hidden_states,
|
1787 |
+
encoder_attention_mask=attention_mask,
|
1788 |
+
head_mask=decoder_head_mask,
|
1789 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
1790 |
+
use_cache=use_cache,
|
1791 |
+
output_attentions=output_attentions,
|
1792 |
+
output_hidden_states=output_hidden_states,
|
1793 |
+
return_dict=return_dict,
|
1794 |
+
)
|
1795 |
+
|
1796 |
+
sequence_output = decoder_outputs[0]
|
1797 |
+
|
1798 |
+
# Set device for model parallelism
|
1799 |
+
if self.model_parallel:
|
1800 |
+
torch.cuda.set_device(self.encoder.first_device)
|
1801 |
+
self.lm_head = self.lm_head.to(self.encoder.first_device)
|
1802 |
+
sequence_output = sequence_output.to(self.lm_head.weight.device)
|
1803 |
+
|
1804 |
+
if self.config.tie_word_embeddings:
|
1805 |
+
# Rescale output before projecting on vocab
|
1806 |
+
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586
|
1807 |
+
sequence_output = sequence_output * (self.model_dim**-0.5)
|
1808 |
+
|
1809 |
+
lm_logits = self.lm_head(sequence_output)
|
1810 |
+
|
1811 |
+
loss = None
|
1812 |
+
if labels is not None:
|
1813 |
+
loss_fct = CrossEntropyLoss(ignore_index=-100)
|
1814 |
+
# move labels to correct device to enable PP
|
1815 |
+
labels = labels.to(lm_logits.device)
|
1816 |
+
loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
|
1817 |
+
# TODO(thom): Add z_loss https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L666
|
1818 |
+
|
1819 |
+
if not return_dict:
|
1820 |
+
output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs
|
1821 |
+
return ((loss,) + output) if loss is not None else output
|
1822 |
+
|
1823 |
+
return Seq2SeqLMOutput(
|
1824 |
+
loss=loss,
|
1825 |
+
logits=lm_logits,
|
1826 |
+
past_key_values=decoder_outputs.past_key_values,
|
1827 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
1828 |
+
decoder_attentions=decoder_outputs.attentions,
|
1829 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
1830 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
1831 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
1832 |
+
encoder_attentions=encoder_outputs.attentions,
|
1833 |
+
)
|
concept--main/dsl.py
ADDED
@@ -0,0 +1,542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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_lines(ctx):
|
6 |
+
rows, cols = len(ctx.grid), len(ctx.grid[0])
|
7 |
+
|
8 |
+
for obj in ctx.objects:
|
9 |
+
columns = {}
|
10 |
+
for r, c in obj[2]:
|
11 |
+
if c not in columns:
|
12 |
+
columns[c] = []
|
13 |
+
columns[c].append(r)
|
14 |
+
|
15 |
+
for c, rows_in_col in columns.items():
|
16 |
+
if len(rows_in_col) > 1:
|
17 |
+
unique_vals = {ctx.grid[r][c] for r in rows_in_col}
|
18 |
+
if len(unique_vals) == 1:
|
19 |
+
for r in rows_in_col:
|
20 |
+
ctx.grid[r][c] = 0
|
21 |
+
return ctx.grid
|
22 |
+
def fill_object_interior(ctx):
|
23 |
+
"""
|
24 |
+
Fills the interior of each object in the GPContext grid.
|
25 |
+
Assumes ctx.objects has been extracted already.
|
26 |
+
"""
|
27 |
+
rows, cols = len(ctx.grid), len(ctx.grid[0])
|
28 |
+
|
29 |
+
for obj in ctx.objects:
|
30 |
+
min_r = min(r for r, c in obj)
|
31 |
+
max_r = max(r for r, c in obj)
|
32 |
+
min_c = min(c for r, c in obj)
|
33 |
+
max_c = max(c for r, c in obj)
|
34 |
+
|
35 |
+
obj_color = ctx.grid[min_r][min_c]
|
36 |
+
fill_color = (obj_color + 1) % 9 or 1 # consistent color, avoid zero
|
37 |
+
|
38 |
+
for r in range(min_r, max_r + 1):
|
39 |
+
for c in range(min_c, max_c + 1):
|
40 |
+
if (r, c) not in obj and ctx.grid[r][c] == 0:
|
41 |
+
ctx.grid[r][c] = fill_color
|
42 |
+
|
43 |
+
return ctx.grid
|
44 |
+
|
45 |
+
def move_right_most_object(ctx):
|
46 |
+
if not ctx.objects:
|
47 |
+
return ctx.grid
|
48 |
+
|
49 |
+
# Get rightmost object: object with largest column index
|
50 |
+
rightmost_object = max(ctx.objects, key=lambda obj: max(y for x, y in obj[2]))
|
51 |
+
_, value, block = rightmost_object
|
52 |
+
|
53 |
+
for x, y in block:
|
54 |
+
ctx.grid[x][y] = 0
|
55 |
+
|
56 |
+
shift = 0
|
57 |
+
cols = len(ctx.grid[0])
|
58 |
+
while True:
|
59 |
+
can_move = True
|
60 |
+
for x, y in block:
|
61 |
+
new_y = y + shift + 1
|
62 |
+
if new_y >= cols or ctx.grid[x][new_y] != 0:
|
63 |
+
can_move = False
|
64 |
+
break
|
65 |
+
if not can_move:
|
66 |
+
break
|
67 |
+
shift += 1
|
68 |
+
|
69 |
+
for x, y in block:
|
70 |
+
ctx.grid[x][y + shift] = value
|
71 |
+
|
72 |
+
return ctx.grid
|
73 |
+
def move_left_most_object(ctx):
|
74 |
+
if not ctx.objects:
|
75 |
+
return ctx.grid
|
76 |
+
|
77 |
+
# Get leftmost object: object with smallest column index
|
78 |
+
leftmost_object = min(ctx.objects, key=lambda obj: min(y for x, y in obj[2]))
|
79 |
+
_, value, block = leftmost_object
|
80 |
+
|
81 |
+
for x, y in block:
|
82 |
+
ctx.grid[x][y] = 0
|
83 |
+
|
84 |
+
shift = 0
|
85 |
+
while True:
|
86 |
+
can_move = True
|
87 |
+
for x, y in block:
|
88 |
+
new_y = y - (shift + 1)
|
89 |
+
if new_y < 0 or ctx.grid[x][new_y] != 0:
|
90 |
+
can_move = False
|
91 |
+
break
|
92 |
+
if not can_move:
|
93 |
+
break
|
94 |
+
shift += 1
|
95 |
+
|
96 |
+
for x, y in block:
|
97 |
+
ctx.grid[x][y - shift] = value
|
98 |
+
|
99 |
+
return ctx.grid
|
100 |
+
|
101 |
+
def move_bottom_most_object(ctx):
|
102 |
+
if not ctx.objects:
|
103 |
+
return ctx.grid
|
104 |
+
|
105 |
+
# Get bottommost object (last one in the list after sorting by top_row)
|
106 |
+
bottom_object = ctx.objects[-1]
|
107 |
+
_, value, block = bottom_object
|
108 |
+
|
109 |
+
# Remove it from the grid
|
110 |
+
for x, y in block:
|
111 |
+
ctx.grid[x][y] = 0
|
112 |
+
|
113 |
+
# Compute shift (same as top, move down)
|
114 |
+
shift = 0
|
115 |
+
rows = len(ctx.grid)
|
116 |
+
while True:
|
117 |
+
can_move = True
|
118 |
+
for x, y in block:
|
119 |
+
new_x = x + shift + 1
|
120 |
+
if new_x >= rows or ctx.grid[new_x][y] != 0:
|
121 |
+
can_move = False
|
122 |
+
break
|
123 |
+
if not can_move:
|
124 |
+
break
|
125 |
+
shift += 1
|
126 |
+
|
127 |
+
# Place object
|
128 |
+
for x, y in block:
|
129 |
+
ctx.grid[x + shift][y] = value
|
130 |
+
|
131 |
+
return ctx.grid
|
132 |
+
def detect_objects(grid):
|
133 |
+
"""
|
134 |
+
Detects objects in an ARC grid.
|
135 |
+
Objects are contiguous regions of the same color (4-connected).
|
136 |
+
Returns a list of objects, where each object is a set of (row, col) coordinates.
|
137 |
+
"""
|
138 |
+
rows, cols = len(grid), len(grid[0])
|
139 |
+
visited = set()
|
140 |
+
objects = []
|
141 |
+
|
142 |
+
def bfs(start_r, start_c, color):
|
143 |
+
""" Perform BFS to find all connected pixels of the same color """
|
144 |
+
queue = deque([(start_r, start_c)])
|
145 |
+
obj_pixels = set()
|
146 |
+
|
147 |
+
while queue:
|
148 |
+
r, c = queue.popleft()
|
149 |
+
if (r, c) in visited:
|
150 |
+
continue
|
151 |
+
|
152 |
+
visited.add((r, c))
|
153 |
+
obj_pixels.add((r, c))
|
154 |
+
|
155 |
+
# Check 4-connected neighbors (up, down, left, right)
|
156 |
+
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
|
157 |
+
nr, nc = r + dr, c + dc
|
158 |
+
if 0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in visited:
|
159 |
+
if grid[nr][nc] == color:
|
160 |
+
queue.append((nr, nc))
|
161 |
+
|
162 |
+
return obj_pixels
|
163 |
+
|
164 |
+
# Iterate over the grid to find objects
|
165 |
+
for r in range(rows):
|
166 |
+
for c in range(cols):
|
167 |
+
if (r, c) not in visited and grid[r][c] != 0: # Ignore background (0)
|
168 |
+
obj = bfs(r, c, grid[r][c])
|
169 |
+
objects.append(obj)
|
170 |
+
|
171 |
+
return objects
|
172 |
+
def highlight_detected_objects(grid):
|
173 |
+
objects = detect_objects(grid)
|
174 |
+
new_grid = [row[:] for row in grid]
|
175 |
+
for idx, obj in enumerate(objects, start=1):
|
176 |
+
for r, c in obj:
|
177 |
+
new_grid[r][c] = (idx % 9) or 1
|
178 |
+
return new_grid
|
179 |
+
|
180 |
+
def fill_object_interior(grid):
|
181 |
+
""" Modifies the grid by filling the interiors of detected objects with a different color."""
|
182 |
+
objects = detect_objects(grid)
|
183 |
+
rows, cols = len(grid), len(grid[0])
|
184 |
+
new_grid = [row[:] for row in grid] # Create a copy of the grid
|
185 |
+
|
186 |
+
for obj in objects:
|
187 |
+
min_r = min(r for r, c in obj)
|
188 |
+
max_r = max(r for r, c in obj)
|
189 |
+
min_c = min(c for r, c in obj)
|
190 |
+
max_c = max(c for r, c in obj)
|
191 |
+
|
192 |
+
# Find a new fill color (incrementing the current color modulo 9 for variation)
|
193 |
+
obj_color = grid[min_r][min_c]
|
194 |
+
fill_color = (obj_color + 1) % 9 if obj_color + 1 != 0 else 1
|
195 |
+
|
196 |
+
# Identify and fill the interior pixels of the object
|
197 |
+
for r in range(min_r, max_r + 1):
|
198 |
+
for c in range(min_c, max_c + 1):
|
199 |
+
if (r, c) not in obj and grid[r][c] == 0: # Empty space inside the object
|
200 |
+
new_grid[r][c] = fill_color
|
201 |
+
|
202 |
+
return new_grid
|
203 |
+
def diamirror(input_grid):
|
204 |
+
return np.transpose(input_grid)
|
205 |
+
|
206 |
+
|
207 |
+
import numpy as np
|
208 |
+
|
209 |
+
def get_object_bounds(grid):
|
210 |
+
grid = np.array(grid)
|
211 |
+
top, bottom = None, None
|
212 |
+
for i in range(grid.shape[0]):
|
213 |
+
if np.any(grid[i] != 0):
|
214 |
+
if top is None:
|
215 |
+
top = i
|
216 |
+
bottom = i
|
217 |
+
return top, bottom
|
218 |
+
def reverse_object_top_bottom(grid):
|
219 |
+
grid = np.array(grid)
|
220 |
+
top, bottom = get_object_bounds(grid)
|
221 |
+
if top is None or bottom is None:
|
222 |
+
return grid
|
223 |
+
grid_copy = np.copy(grid)
|
224 |
+
grid_copy[top:bottom+1] = np.flipud(grid[top:bottom+1])
|
225 |
+
return grid_copy
|
226 |
+
|
227 |
+
def hmirror(input_grid: np.ndarray) -> np.ndarray:
|
228 |
+
return np.fliplr(input_grid)
|
229 |
+
|
230 |
+
def vmirrors(input_grid: np.ndarray) -> np.ndarray:
|
231 |
+
return np.flipud(input_grid)
|
232 |
+
|
233 |
+
def flip_horizontal(input_grid: np.ndarray) -> np.ndarray:
|
234 |
+
return np.fliplr(input_grid)
|
235 |
+
|
236 |
+
def flip_vertical(input_grid: np.ndarray) -> np.ndarray:
|
237 |
+
return np.flipud(input_grid)
|
238 |
+
|
239 |
+
def rotate_90(input_grid: np.ndarray) -> np.ndarray:
|
240 |
+
return np.rot90(input_grid, k=-1)
|
241 |
+
|
242 |
+
def rotate_180(input_grid: np.ndarray) -> np.ndarray:
|
243 |
+
return np.rot90(input_grid, k=2)
|
244 |
+
|
245 |
+
def rotate_270(input_grid: np.ndarray) -> np.ndarray:
|
246 |
+
return np.rot90(input_grid, k=1)
|
247 |
+
|
248 |
+
def identity(input_grid: np.ndarray) -> np.ndarray:
|
249 |
+
return input_grid
|
250 |
+
def find_center_pixel(grid):
|
251 |
+
"""Finds the center pixel of the input grid and returns it as a 1x1 output grid."""
|
252 |
+
center_index = len(grid[0]) // 2 # Get the middle index
|
253 |
+
return [[grid[0][center_index]]] # Return as a 1x1 grid with the center pixel
|
254 |
+
|
255 |
+
# --- Object Detection and Manipulation ---
|
256 |
+
def detect_objects(grid):
|
257 |
+
"""Detects objects in the grid and returns a list of bounding boxes and pixel coordinates."""
|
258 |
+
height, width = len(grid), len(grid[0])
|
259 |
+
visited = set()
|
260 |
+
objects = []
|
261 |
+
|
262 |
+
def bfs(r, c, color):
|
263 |
+
"""Finds all pixels belonging to an object using BFS."""
|
264 |
+
queue = [(r, c)]
|
265 |
+
pixels = [] # Use a list instead of a set
|
266 |
+
min_r, max_r, min_c, max_c = r, r, c, c
|
267 |
+
|
268 |
+
while queue:
|
269 |
+
x, y = queue.pop(0)
|
270 |
+
if (x, y) in visited:
|
271 |
+
continue
|
272 |
+
visited.add((x, y))
|
273 |
+
pixels.append((x, y)) # Append to list
|
274 |
+
min_r, max_r = min(min_r, x), max(max_r, x)
|
275 |
+
min_c, max_c = min(min_c, y), max(max_c, y)
|
276 |
+
|
277 |
+
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # Only vertical & horizontal connections
|
278 |
+
nx, ny = x + dx, y + dy
|
279 |
+
if (0 <= nx < height and 0 <= ny < width and (nx, ny) not in visited and grid[nx][ny] == color):
|
280 |
+
queue.append((nx, ny))
|
281 |
+
|
282 |
+
return (min_r, max_r, min_c, max_c, color, pixels) # Return tuple, pixels as a list
|
283 |
+
|
284 |
+
for r in range(height):
|
285 |
+
for c in range(width):
|
286 |
+
if grid[r][c] != 0 and (r, c) not in visited:
|
287 |
+
visited.add((r, c))
|
288 |
+
objects.append(bfs(r, c, grid[r][c])) # Append tuple to list
|
289 |
+
|
290 |
+
return objects # Ensure `objects` is a list, not a set
|
291 |
+
|
292 |
+
def extract_bottom_object(grid):
|
293 |
+
"""Extracts the bottom-most object from the grid, crops it, and returns it as a new grid."""
|
294 |
+
objects = detect_objects(grid)
|
295 |
+
if not objects:
|
296 |
+
return grid
|
297 |
+
|
298 |
+
bottom_object = max(objects, key=lambda obj: obj[1]) # obj[1] is max_r
|
299 |
+
min_r, max_r, min_c, max_c, obj_color, pixels = bottom_object
|
300 |
+
cropped_height = max_r - min_r + 1
|
301 |
+
cropped_width = max_c - min_c + 1
|
302 |
+
cropped_grid = np.zeros((cropped_height, cropped_width), dtype=int)
|
303 |
+
|
304 |
+
for r, c in pixels:
|
305 |
+
cropped_grid[r - min_r, c - min_c] = obj_color
|
306 |
+
|
307 |
+
return cropped_grid.tolist()
|
308 |
+
|
309 |
+
def keep_bottom_object(grid):
|
310 |
+
"""Keeps only the bottom-most object and removes all others."""
|
311 |
+
height, width = len(grid), len(grid[0])
|
312 |
+
objects = detect_objects(grid)
|
313 |
+
output_grid = np.zeros((height, width), dtype=int)
|
314 |
+
|
315 |
+
if not objects:
|
316 |
+
return output_grid.tolist()
|
317 |
+
|
318 |
+
bottom_object = max(objects, key=lambda obj: obj[1]) # obj[1] is max_r
|
319 |
+
|
320 |
+
for r, c in bottom_object[5]: # obj[5] contains pixels
|
321 |
+
output_grid[r][c] = bottom_object[4] # obj[4] is color
|
322 |
+
|
323 |
+
return output_grid.tolist()
|
324 |
+
|
325 |
+
def recolor_to_bottom_object(grid):
|
326 |
+
"""Recolors all objects to match the color of the bottom-most object."""
|
327 |
+
height, width = len(grid), len(grid[0])
|
328 |
+
objects = detect_objects(grid)
|
329 |
+
output_grid = np.array(grid)
|
330 |
+
|
331 |
+
if not objects:
|
332 |
+
return output_grid.tolist()
|
333 |
+
|
334 |
+
bottom_object = max(objects, key=lambda obj: obj[1]) # obj[1] is max_r
|
335 |
+
bottom_color = bottom_object[4] # obj[4] is color
|
336 |
+
|
337 |
+
for min_r, max_r, min_c, max_c, obj_color, pixels in objects:
|
338 |
+
for r, c in pixels:
|
339 |
+
output_grid[r][c] = bottom_color # Change to bottom-most object's color
|
340 |
+
|
341 |
+
return output_grid.tolist()
|
342 |
+
|
343 |
+
def remove_top_bottom_objects(grid):
|
344 |
+
"""Removes objects that touch either the top or bottom of the grid."""
|
345 |
+
height, width = len(grid), len(grid[0])
|
346 |
+
objects = detect_objects(grid)
|
347 |
+
output_grid = np.zeros((height, width), dtype=int)
|
348 |
+
|
349 |
+
if not objects:
|
350 |
+
return output_grid.tolist()
|
351 |
+
|
352 |
+
min_top = min(obj[0] for obj in objects)
|
353 |
+
max_bottom = max(obj[1] for obj in objects)
|
354 |
+
|
355 |
+
for (min_r, max_r, min_c, max_c, obj_color, pixels) in objects:
|
356 |
+
if min_r == min_top or max_r == max_bottom:
|
357 |
+
continue
|
358 |
+
for r, c in pixels:
|
359 |
+
output_grid[r][c] = obj_color
|
360 |
+
|
361 |
+
return output_grid.tolist()
|
362 |
+
|
363 |
+
def extract_topmost_object(grid):
|
364 |
+
"""Extracts the top-most object from the grid, crops it, and returns it as a new grid."""
|
365 |
+
objects = detect_objects(grid)
|
366 |
+
if not objects:
|
367 |
+
return grid
|
368 |
+
|
369 |
+
topmost_object = min(objects, key=lambda obj: obj[0]) # obj[0] is min_r
|
370 |
+
min_r, max_r, min_c, max_c, obj_color, pixels = topmost_object
|
371 |
+
cropped_height = max_r - min_r + 1
|
372 |
+
cropped_width = max_c - min_c + 1
|
373 |
+
cropped_grid = np.zeros((cropped_height, cropped_width), dtype=int)
|
374 |
+
|
375 |
+
for r, c in pixels:
|
376 |
+
cropped_grid[r - min_r, c - min_c] = obj_color
|
377 |
+
|
378 |
+
return cropped_grid.tolist()
|
379 |
+
|
380 |
+
def swap_objects(grid):
|
381 |
+
"""Swaps detected objects in the grid."""
|
382 |
+
objects = detect_objects(grid)
|
383 |
+
objects = sorted(objects, key=lambda obj: obj[1]) # Sort by vertical position
|
384 |
+
|
385 |
+
object_positions = [obj[5] for obj in objects] # obj[5] contains pixels
|
386 |
+
object_colors = [obj[4] for obj in objects] # obj[4] is color
|
387 |
+
swapped_positions = object_positions[::-1]
|
388 |
+
|
389 |
+
new_grid = np.zeros_like(grid)
|
390 |
+
for color, new_positions in zip(object_colors, swapped_positions):
|
391 |
+
for r, c in new_positions:
|
392 |
+
new_grid[r][c] = color
|
393 |
+
|
394 |
+
return new_grid.tolist()
|
395 |
+
|
396 |
+
# --- Pixel & Color Manipulation ---
|
397 |
+
def transform_blue_to_red(input_grid):
|
398 |
+
"""Transforms all blue (1) pixels to red (2)."""
|
399 |
+
grid = np.array(input_grid)
|
400 |
+
return np.where(grid == 1, 2, grid).tolist()
|
401 |
+
|
402 |
+
def fill_downward(grid):
|
403 |
+
"""Fills non-zero pixels downward, propagating their colors downwards in each column."""
|
404 |
+
height, width = len(grid), len(grid[0])
|
405 |
+
output_grid = np.array(grid)
|
406 |
+
|
407 |
+
for col in range(width):
|
408 |
+
fill_color = 0
|
409 |
+
for row in range(height):
|
410 |
+
if grid[row][col] != 0:
|
411 |
+
fill_color = grid[row][col]
|
412 |
+
if fill_color != 0:
|
413 |
+
output_grid[row][col] = fill_color
|
414 |
+
return output_grid.tolist()
|
415 |
+
|
416 |
+
def remove_below_horizontal_line(grid):
|
417 |
+
"""Detects the first fully connected horizontal line and removes everything below it."""
|
418 |
+
height, width = len(grid), len(grid[0])
|
419 |
+
output_grid = np.array(grid)
|
420 |
+
|
421 |
+
for row in range(height):
|
422 |
+
if np.all(output_grid[row] != 0):
|
423 |
+
output_grid[row + 1:] = 0
|
424 |
+
break
|
425 |
+
return output_grid.tolist()
|
426 |
+
|
427 |
+
def find_center_pixel(grid):
|
428 |
+
"""Finds the center of the grid and returns it as a 1x1 pixel grid."""
|
429 |
+
center_index = len(grid[0]) // 2
|
430 |
+
return [[grid[0][center_index]]]
|
431 |
+
|
432 |
+
def extract_largest_row(grid):
|
433 |
+
"""Finds the row with the most non-zero elements and extracts it."""
|
434 |
+
grid = np.array(grid)
|
435 |
+
max_length = 0
|
436 |
+
longest_row = []
|
437 |
+
|
438 |
+
for row in grid:
|
439 |
+
row_values = row[row > 0]
|
440 |
+
if len(row_values) > max_length:
|
441 |
+
max_length = len(row_values)
|
442 |
+
longest_row = row_values.tolist()
|
443 |
+
return [longest_row]
|
444 |
+
|
445 |
+
def extract_dominant_colors(grid):
|
446 |
+
"""Finds the two most dominant non-zero colors in the grid."""
|
447 |
+
flattened = [cell for row in grid for cell in row if cell != 0]
|
448 |
+
color_counts = Counter(flattened)
|
449 |
+
|
450 |
+
if not color_counts:
|
451 |
+
return [[]]
|
452 |
+
most_common_colors = [color for color, _ in color_counts.most_common(2)]
|
453 |
+
return [[color for color in most_common_colors]]
|
454 |
+
|
455 |
+
def remove_dominant_color(grid):
|
456 |
+
"""Removes the most dominant color from the grid."""
|
457 |
+
color_counts = Counter(cell for row in grid for cell in row if cell != 0)
|
458 |
+
|
459 |
+
if color_counts:
|
460 |
+
dominant_color = max(color_counts, key=color_counts.get)
|
461 |
+
else:
|
462 |
+
return grid
|
463 |
+
return [[0 if cell == dominant_color else cell for cell in row] for row in grid]
|
464 |
+
|
465 |
+
def find_least_dominant_pixel(grid):
|
466 |
+
"""Finds the least occurring non-zero pixel in the grid."""
|
467 |
+
pixel_counts = {}
|
468 |
+
|
469 |
+
for row in grid:
|
470 |
+
for value in row:
|
471 |
+
if value != 0:
|
472 |
+
pixel_counts[value] = pixel_counts.get(value, 0) + 1
|
473 |
+
|
474 |
+
if not pixel_counts:
|
475 |
+
return None
|
476 |
+
|
477 |
+
return min(pixel_counts, key=pixel_counts.get)
|
478 |
+
|
479 |
+
def remove_least_dominant_pixel(grid):
|
480 |
+
"""Removes the least dominant pixel from the grid."""
|
481 |
+
rows, cols = len(grid), len(grid[0])
|
482 |
+
least_dominant_pixel = find_least_dominant_pixel(grid)
|
483 |
+
|
484 |
+
if least_dominant_pixel is None:
|
485 |
+
return grid
|
486 |
+
|
487 |
+
new_grid = np.array(grid)
|
488 |
+
for x in range(rows):
|
489 |
+
for y in range(cols):
|
490 |
+
if grid[x][y] == least_dominant_pixel:
|
491 |
+
new_grid[x, y] = 0
|
492 |
+
return new_grid.tolist()
|
493 |
+
|
494 |
+
def upscale(input_grid, upscale_factor=3):
|
495 |
+
"""Upscales the grid by expanding each pixel into a 3x3 block."""
|
496 |
+
def expand_pixel_with_grid(pixel, input_grid):
|
497 |
+
if pixel == 0:
|
498 |
+
return np.zeros((upscale_factor, upscale_factor), dtype=int)
|
499 |
+
else:
|
500 |
+
return input_grid
|
501 |
+
|
502 |
+
input_rows, input_cols = len(input_grid), len(input_grid[0])
|
503 |
+
output_grid = np.zeros((input_rows * upscale_factor, input_cols * upscale_factor), dtype=int)
|
504 |
+
|
505 |
+
for r in range(input_rows):
|
506 |
+
for c in range(input_cols):
|
507 |
+
expanded_block = expand_pixel_with_grid(input_grid[r][c], input_grid)
|
508 |
+
output_grid[r * upscale_factor: (r + 1) * upscale_factor, c * upscale_factor: (c + 1) * upscale_factor] = expanded_block
|
509 |
+
|
510 |
+
return output_grid
|
511 |
+
|
512 |
+
def remove_center_object(grid):
|
513 |
+
"""Removes anything located at the center of the grid."""
|
514 |
+
height, width = len(grid), len(grid[0])
|
515 |
+
center_r, center_c = height // 2, width // 2
|
516 |
+
grid = np.array(grid)
|
517 |
+
|
518 |
+
center_value = grid[center_r, center_c]
|
519 |
+
if center_value != 0:
|
520 |
+
grid[grid == center_value] = 0
|
521 |
+
return grid.tolist()
|
522 |
+
import numpy as np
|
523 |
+
|
524 |
+
def draw_horizontal_vertical(grid):
|
525 |
+
"""Adds a horizontal or vertical line of 8s based on object orientation."""
|
526 |
+
if grid is None or len(grid) == 0 or len(grid[0]) == 0:
|
527 |
+
print("ERROR: Grid is empty. Cannot apply draw_horizontal_vertical.")
|
528 |
+
return grid
|
529 |
+
|
530 |
+
rows, cols = len(grid), len(grid[0])
|
531 |
+
print(f"Grid Shape Before Modification: {rows}x{cols}") # Debugging Info
|
532 |
+
|
533 |
+
new_grid = np.array(grid)
|
534 |
+
|
535 |
+
for r in range(rows):
|
536 |
+
new_grid[r][-1] = 8 # Rightmost column
|
537 |
+
|
538 |
+
for c in range(cols):
|
539 |
+
new_grid[0][c] = 8 # Topmost row
|
540 |
+
|
541 |
+
return new_grid.tolist()
|
542 |
+
|
concept--main/fittnes.py
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from typing import List, Tuple
|
3 |
+
from Node import Node
|
4 |
+
|
5 |
+
def evaluate_fitness(program: Node, input_output_pairs: List[Tuple[np.ndarray, np.ndarray]]) -> int:
|
6 |
+
fitness = 0
|
7 |
+
for input_grid, expected_output in input_output_pairs:
|
8 |
+
try:
|
9 |
+
output = program.evaluate(input_grid)
|
10 |
+
if np.array_equal(output, expected_output):
|
11 |
+
fitness += 1
|
12 |
+
except Exception as e:
|
13 |
+
print(f"Error during fitness evaluation: {e}")
|
14 |
+
pass
|
15 |
+
return fitness
|
concept--main/interface.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
|
4 |
+
from flask import Flask, request, jsonify
|
5 |
+
from Vit_concept import run_inference, model
|
6 |
+
from GP import genetic_programming
|
7 |
+
import traceback
|
8 |
+
import os
|
9 |
+
|
10 |
+
app = Flask(__name__)
|
11 |
+
|
12 |
+
@app.route('/')
|
13 |
+
def home():
|
14 |
+
return "API is running."
|
15 |
+
|
16 |
+
@app.route('/run', methods=['POST'])
|
17 |
+
def run_model():
|
18 |
+
try:
|
19 |
+
data = request.get_json(force=True) # force=True handles edge cases where headers are weird
|
20 |
+
input_output_pairs = []
|
21 |
+
predicted_HLCs = []
|
22 |
+
|
23 |
+
# Debugging: Log sample count
|
24 |
+
print(f"Received {len(data.get('train', []))} training samples")
|
25 |
+
|
26 |
+
for sample in data["train"]:
|
27 |
+
input_grid = sample["input"]
|
28 |
+
output_grid = sample["output"]
|
29 |
+
|
30 |
+
# Debug step
|
31 |
+
print("Running run_inference on a sample...")
|
32 |
+
concept_label, *_ = run_inference(model, input_grid, output_grid)
|
33 |
+
predicted_HLCs.append(concept_label)
|
34 |
+
input_output_pairs.append((input_grid, output_grid))
|
35 |
+
|
36 |
+
predicted_HLCs = list(set(predicted_HLCs))
|
37 |
+
|
38 |
+
print("Calling genetic_programming...")
|
39 |
+
best_program, generations = genetic_programming(
|
40 |
+
input_output_pairs=input_output_pairs,
|
41 |
+
population_size=30,
|
42 |
+
generations=10,
|
43 |
+
mutation_rate=0.2,
|
44 |
+
crossover_rate=0.7,
|
45 |
+
max_depth=3,
|
46 |
+
predicted_HLCs=predicted_HLCs
|
47 |
+
)
|
48 |
+
|
49 |
+
print("Returning response...")
|
50 |
+
return jsonify({
|
51 |
+
"best_program": str(best_program)
|
52 |
+
})
|
53 |
+
except Exception as e:
|
54 |
+
print("🔥 ERROR in /run route!")
|
55 |
+
print(traceback.format_exc()) # Show full error trace in Render logs
|
56 |
+
return jsonify({"error": str(e)}), 500
|
57 |
+
|
58 |
+
if __name__ == "__main__":
|
59 |
+
port = int(os.environ.get("PORT", 10000))
|
60 |
+
print(f"Starting server on port {port}...")
|
61 |
+
app.run(host="0.0.0.0", port=port)
|
concept--main/model/final_cls_model
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
concept--main/model/final_cls_modell.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:486ab5a17386db9931588c63636f732a53716f25347b41954f67ba47bc79c5be
|
3 |
+
size 11069076
|
concept--main/requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Flask
|
2 |
+
Flask-Cors
|
3 |
+
torch
|
4 |
+
numpy
|
5 |
+
scikit-learn
|
6 |
+
transformers
|
7 |
+
pandas
|
8 |
+
matplotlib
|
9 |
+
numpy
|
concept--main/task_loader.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import matplotlib.pyplot as plt
|
3 |
+
from matplotlib import colors
|
4 |
+
import os
|
5 |
+
import json
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
#Notes
|
9 |
+
|
10 |
+
" directory_path:str keeps the path containing the tasks"
|
11 |
+
"tasks:list of tuples containing the the task filename and the task data "
|
12 |
+
"task_idx:index of the current task in the current iteration"
|
13 |
+
"task_file name:str name of the task file being processed"
|
14 |
+
"task_data: dictionary containing the task data basically the input and the output grids"
|
15 |
+
"input_output_pairs: list of tuples containing the input and the output grids"
|
16 |
+
|
17 |
+
def load_tasks_from_directory(directory_path):
|
18 |
+
tasks = []
|
19 |
+
for filename in os.listdir(directory_path):
|
20 |
+
if filename.endswith(".json"):
|
21 |
+
filepath = os.path.join(directory_path, filename)
|
22 |
+
with open(filepath, 'r') as file:
|
23 |
+
task_data = json.load(file)
|
24 |
+
tasks.append((filename, task_data))
|
25 |
+
return tasks
|
26 |
+
|
27 |
+
def prepare_input_output_pairs(task_data):
|
28 |
+
input_output_pairs = []
|
29 |
+
for example in task_data["train"]:
|
30 |
+
input_grid = np.array(example["input"], dtype=int)
|
31 |
+
output_grid = np.array(example["output"], dtype=int)
|
32 |
+
input_output_pairs.append((input_grid, output_grid))
|
33 |
+
return input_output_pairs
|
concept--main/tokenizer_vs22_extendarctokens/special_tokens_map.json
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<s>",
|
3 |
+
"cls_token": "<cls>",
|
4 |
+
"eos_token": "</s>",
|
5 |
+
"mask_token": "<mask>",
|
6 |
+
"pad_token": "<pad>",
|
7 |
+
"sep_token": "<sep>",
|
8 |
+
"unk_token": "<unk>"
|
9 |
+
}
|
concept--main/tokenizer_vs22_extendarctokens/tokenizer.json
ADDED
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
"content": "<s>",
|
9 |
+
"single_word": false,
|
10 |
+
"lstrip": false,
|
11 |
+
"rstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"special": true
|
14 |
+
},
|
15 |
+
{
|
16 |
+
"id": 1,
|
17 |
+
"content": "</s>",
|
18 |
+
"single_word": false,
|
19 |
+
"lstrip": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"normalized": false,
|
22 |
+
"special": true
|
23 |
+
},
|
24 |
+
{
|
25 |
+
"id": 2,
|
26 |
+
"content": "<unk>",
|
27 |
+
"single_word": false,
|
28 |
+
"lstrip": false,
|
29 |
+
"rstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"special": true
|
32 |
+
},
|
33 |
+
{
|
34 |
+
"id": 3,
|
35 |
+
"content": "<cls>",
|
36 |
+
"single_word": false,
|
37 |
+
"lstrip": false,
|
38 |
+
"rstrip": false,
|
39 |
+
"normalized": false,
|
40 |
+
"special": true
|
41 |
+
},
|
42 |
+
{
|
43 |
+
"id": 4,
|
44 |
+
"content": "<sep>",
|
45 |
+
"single_word": false,
|
46 |
+
"lstrip": false,
|
47 |
+
"rstrip": false,
|
48 |
+
"normalized": false,
|
49 |
+
"special": true
|
50 |
+
},
|
51 |
+
{
|
52 |
+
"id": 5,
|
53 |
+
"content": "<pad>",
|
54 |
+
"single_word": false,
|
55 |
+
"lstrip": false,
|
56 |
+
"rstrip": false,
|
57 |
+
"normalized": false,
|
58 |
+
"special": true
|
59 |
+
},
|
60 |
+
{
|
61 |
+
"id": 6,
|
62 |
+
"content": "<mask>",
|
63 |
+
"single_word": false,
|
64 |
+
"lstrip": false,
|
65 |
+
"rstrip": false,
|
66 |
+
"normalized": false,
|
67 |
+
"special": true
|
68 |
+
},
|
69 |
+
{
|
70 |
+
"id": 7,
|
71 |
+
"content": "<arc_0>",
|
72 |
+
"single_word": false,
|
73 |
+
"lstrip": false,
|
74 |
+
"rstrip": false,
|
75 |
+
"normalized": true,
|
76 |
+
"special": false
|
77 |
+
},
|
78 |
+
{
|
79 |
+
"id": 8,
|
80 |
+
"content": "<arc_1>",
|
81 |
+
"single_word": false,
|
82 |
+
"lstrip": false,
|
83 |
+
"rstrip": false,
|
84 |
+
"normalized": true,
|
85 |
+
"special": false
|
86 |
+
},
|
87 |
+
{
|
88 |
+
"id": 9,
|
89 |
+
"content": "<arc_2>",
|
90 |
+
"single_word": false,
|
91 |
+
"lstrip": false,
|
92 |
+
"rstrip": false,
|
93 |
+
"normalized": true,
|
94 |
+
"special": false
|
95 |
+
},
|
96 |
+
{
|
97 |
+
"id": 10,
|
98 |
+
"content": "<arc_3>",
|
99 |
+
"single_word": false,
|
100 |
+
"lstrip": false,
|
101 |
+
"rstrip": false,
|
102 |
+
"normalized": true,
|
103 |
+
"special": false
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"id": 11,
|
107 |
+
"content": "<arc_4>",
|
108 |
+
"single_word": false,
|
109 |
+
"lstrip": false,
|
110 |
+
"rstrip": false,
|
111 |
+
"normalized": true,
|
112 |
+
"special": false
|
113 |
+
},
|
114 |
+
{
|
115 |
+
"id": 12,
|
116 |
+
"content": "<arc_5>",
|
117 |
+
"single_word": false,
|
118 |
+
"lstrip": false,
|
119 |
+
"rstrip": false,
|
120 |
+
"normalized": true,
|
121 |
+
"special": false
|
122 |
+
},
|
123 |
+
{
|
124 |
+
"id": 13,
|
125 |
+
"content": "<arc_6>",
|
126 |
+
"single_word": false,
|
127 |
+
"lstrip": false,
|
128 |
+
"rstrip": false,
|
129 |
+
"normalized": true,
|
130 |
+
"special": false
|
131 |
+
},
|
132 |
+
{
|
133 |
+
"id": 14,
|
134 |
+
"content": "<arc_7>",
|
135 |
+
"single_word": false,
|
136 |
+
"lstrip": false,
|
137 |
+
"rstrip": false,
|
138 |
+
"normalized": true,
|
139 |
+
"special": false
|
140 |
+
},
|
141 |
+
{
|
142 |
+
"id": 15,
|
143 |
+
"content": "<arc_8>",
|
144 |
+
"single_word": false,
|
145 |
+
"lstrip": false,
|
146 |
+
"rstrip": false,
|
147 |
+
"normalized": true,
|
148 |
+
"special": false
|
149 |
+
},
|
150 |
+
{
|
151 |
+
"id": 16,
|
152 |
+
"content": "<arc_9>",
|
153 |
+
"single_word": false,
|
154 |
+
"lstrip": false,
|
155 |
+
"rstrip": false,
|
156 |
+
"normalized": true,
|
157 |
+
"special": false
|
158 |
+
},
|
159 |
+
{
|
160 |
+
"id": 17,
|
161 |
+
"content": "<arc_endxgrid>",
|
162 |
+
"single_word": false,
|
163 |
+
"lstrip": false,
|
164 |
+
"rstrip": false,
|
165 |
+
"normalized": true,
|
166 |
+
"special": false
|
167 |
+
},
|
168 |
+
{
|
169 |
+
"id": 18,
|
170 |
+
"content": "<arc_endygrid>",
|
171 |
+
"single_word": false,
|
172 |
+
"lstrip": false,
|
173 |
+
"rstrip": false,
|
174 |
+
"normalized": true,
|
175 |
+
"special": false
|
176 |
+
},
|
177 |
+
{
|
178 |
+
"id": 19,
|
179 |
+
"content": "<arc_endxygrid>",
|
180 |
+
"single_word": false,
|
181 |
+
"lstrip": false,
|
182 |
+
"rstrip": false,
|
183 |
+
"normalized": true,
|
184 |
+
"special": false
|
185 |
+
},
|
186 |
+
{
|
187 |
+
"id": 20,
|
188 |
+
"content": "<arc_pad>",
|
189 |
+
"single_word": false,
|
190 |
+
"lstrip": false,
|
191 |
+
"rstrip": false,
|
192 |
+
"normalized": true,
|
193 |
+
"special": false
|
194 |
+
},
|
195 |
+
{
|
196 |
+
"id": 21,
|
197 |
+
"content": "<arc_nl>",
|
198 |
+
"single_word": false,
|
199 |
+
"lstrip": false,
|
200 |
+
"rstrip": false,
|
201 |
+
"normalized": true,
|
202 |
+
"special": false
|
203 |
+
}
|
204 |
+
],
|
205 |
+
"normalizer": {
|
206 |
+
"type": "Sequence",
|
207 |
+
"normalizers": [
|
208 |
+
{
|
209 |
+
"type": "NFD"
|
210 |
+
},
|
211 |
+
{
|
212 |
+
"type": "StripAccents"
|
213 |
+
}
|
214 |
+
]
|
215 |
+
},
|
216 |
+
"pre_tokenizer": {
|
217 |
+
"type": "Whitespace"
|
218 |
+
},
|
219 |
+
"post_processor": null,
|
220 |
+
"decoder": null,
|
221 |
+
"model": {
|
222 |
+
"type": "BPE",
|
223 |
+
"dropout": null,
|
224 |
+
"unk_token": "<unk>",
|
225 |
+
"continuing_subword_prefix": null,
|
226 |
+
"end_of_word_suffix": null,
|
227 |
+
"fuse_unk": false,
|
228 |
+
"byte_fallback": false,
|
229 |
+
"ignore_merges": false,
|
230 |
+
"vocab": {
|
231 |
+
"<s>": 0,
|
232 |
+
"</s>": 1,
|
233 |
+
"<unk>": 2,
|
234 |
+
"<cls>": 3,
|
235 |
+
"<sep>": 4,
|
236 |
+
"<pad>": 5,
|
237 |
+
"<mask>": 6
|
238 |
+
},
|
239 |
+
"merges": []
|
240 |
+
}
|
241 |
+
}
|
concept--main/tokenizer_vs22_extendarctokens/tokenizer_config.json
ADDED
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {
|
3 |
+
"0": {
|
4 |
+
"content": "<s>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": true
|
10 |
+
},
|
11 |
+
"1": {
|
12 |
+
"content": "</s>",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": false,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false,
|
17 |
+
"special": true
|
18 |
+
},
|
19 |
+
"2": {
|
20 |
+
"content": "<unk>",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": false,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false,
|
25 |
+
"special": true
|
26 |
+
},
|
27 |
+
"3": {
|
28 |
+
"content": "<cls>",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false,
|
33 |
+
"special": true
|
34 |
+
},
|
35 |
+
"4": {
|
36 |
+
"content": "<sep>",
|
37 |
+
"lstrip": false,
|
38 |
+
"normalized": false,
|
39 |
+
"rstrip": false,
|
40 |
+
"single_word": false,
|
41 |
+
"special": true
|
42 |
+
},
|
43 |
+
"5": {
|
44 |
+
"content": "<pad>",
|
45 |
+
"lstrip": false,
|
46 |
+
"normalized": false,
|
47 |
+
"rstrip": false,
|
48 |
+
"single_word": false,
|
49 |
+
"special": true
|
50 |
+
},
|
51 |
+
"6": {
|
52 |
+
"content": "<mask>",
|
53 |
+
"lstrip": false,
|
54 |
+
"normalized": false,
|
55 |
+
"rstrip": false,
|
56 |
+
"single_word": false,
|
57 |
+
"special": true
|
58 |
+
},
|
59 |
+
"7": {
|
60 |
+
"content": "<arc_0>",
|
61 |
+
"lstrip": false,
|
62 |
+
"normalized": true,
|
63 |
+
"rstrip": false,
|
64 |
+
"single_word": false,
|
65 |
+
"special": false
|
66 |
+
},
|
67 |
+
"8": {
|
68 |
+
"content": "<arc_1>",
|
69 |
+
"lstrip": false,
|
70 |
+
"normalized": true,
|
71 |
+
"rstrip": false,
|
72 |
+
"single_word": false,
|
73 |
+
"special": false
|
74 |
+
},
|
75 |
+
"9": {
|
76 |
+
"content": "<arc_2>",
|
77 |
+
"lstrip": false,
|
78 |
+
"normalized": true,
|
79 |
+
"rstrip": false,
|
80 |
+
"single_word": false,
|
81 |
+
"special": false
|
82 |
+
},
|
83 |
+
"10": {
|
84 |
+
"content": "<arc_3>",
|
85 |
+
"lstrip": false,
|
86 |
+
"normalized": true,
|
87 |
+
"rstrip": false,
|
88 |
+
"single_word": false,
|
89 |
+
"special": false
|
90 |
+
},
|
91 |
+
"11": {
|
92 |
+
"content": "<arc_4>",
|
93 |
+
"lstrip": false,
|
94 |
+
"normalized": true,
|
95 |
+
"rstrip": false,
|
96 |
+
"single_word": false,
|
97 |
+
"special": false
|
98 |
+
},
|
99 |
+
"12": {
|
100 |
+
"content": "<arc_5>",
|
101 |
+
"lstrip": false,
|
102 |
+
"normalized": true,
|
103 |
+
"rstrip": false,
|
104 |
+
"single_word": false,
|
105 |
+
"special": false
|
106 |
+
},
|
107 |
+
"13": {
|
108 |
+
"content": "<arc_6>",
|
109 |
+
"lstrip": false,
|
110 |
+
"normalized": true,
|
111 |
+
"rstrip": false,
|
112 |
+
"single_word": false,
|
113 |
+
"special": false
|
114 |
+
},
|
115 |
+
"14": {
|
116 |
+
"content": "<arc_7>",
|
117 |
+
"lstrip": false,
|
118 |
+
"normalized": true,
|
119 |
+
"rstrip": false,
|
120 |
+
"single_word": false,
|
121 |
+
"special": false
|
122 |
+
},
|
123 |
+
"15": {
|
124 |
+
"content": "<arc_8>",
|
125 |
+
"lstrip": false,
|
126 |
+
"normalized": true,
|
127 |
+
"rstrip": false,
|
128 |
+
"single_word": false,
|
129 |
+
"special": false
|
130 |
+
},
|
131 |
+
"16": {
|
132 |
+
"content": "<arc_9>",
|
133 |
+
"lstrip": false,
|
134 |
+
"normalized": true,
|
135 |
+
"rstrip": false,
|
136 |
+
"single_word": false,
|
137 |
+
"special": false
|
138 |
+
},
|
139 |
+
"17": {
|
140 |
+
"content": "<arc_endxgrid>",
|
141 |
+
"lstrip": false,
|
142 |
+
"normalized": true,
|
143 |
+
"rstrip": false,
|
144 |
+
"single_word": false,
|
145 |
+
"special": false
|
146 |
+
},
|
147 |
+
"18": {
|
148 |
+
"content": "<arc_endygrid>",
|
149 |
+
"lstrip": false,
|
150 |
+
"normalized": true,
|
151 |
+
"rstrip": false,
|
152 |
+
"single_word": false,
|
153 |
+
"special": false
|
154 |
+
},
|
155 |
+
"19": {
|
156 |
+
"content": "<arc_endxygrid>",
|
157 |
+
"lstrip": false,
|
158 |
+
"normalized": true,
|
159 |
+
"rstrip": false,
|
160 |
+
"single_word": false,
|
161 |
+
"special": false
|
162 |
+
},
|
163 |
+
"20": {
|
164 |
+
"content": "<arc_pad>",
|
165 |
+
"lstrip": false,
|
166 |
+
"normalized": true,
|
167 |
+
"rstrip": false,
|
168 |
+
"single_word": false,
|
169 |
+
"special": false
|
170 |
+
},
|
171 |
+
"21": {
|
172 |
+
"content": "<arc_nl>",
|
173 |
+
"lstrip": false,
|
174 |
+
"normalized": true,
|
175 |
+
"rstrip": false,
|
176 |
+
"single_word": false,
|
177 |
+
"special": false
|
178 |
+
}
|
179 |
+
},
|
180 |
+
"bos_token": "<s>",
|
181 |
+
"clean_up_tokenization_spaces": true,
|
182 |
+
"cls_token": "<cls>",
|
183 |
+
"eos_token": "</s>",
|
184 |
+
"mask_token": "<mask>",
|
185 |
+
"model_max_length": 1000000000000000019884624838656,
|
186 |
+
"pad_token": "<pad>",
|
187 |
+
"padding_side": "right",
|
188 |
+
"sep_token": "<sep>",
|
189 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
190 |
+
"truncation_side": "right",
|
191 |
+
"unk_token": "<unk>"
|
192 |
+
}
|
concept--main/tokenizer_vs22_extendarctokens/tt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
concept--main/utils.py
ADDED
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import matplotlib.pyplot as plt
|
2 |
+
from matplotlib.colors import ListedColormap, Normalize
|
3 |
+
|
4 |
+
from random import choice, randint, sample, shuffle, uniform
|
5 |
+
|
6 |
+
from dsl import *
|
7 |
+
|
8 |
+
|
9 |
+
global rng
|
10 |
+
rng = []
|
11 |
+
|
12 |
+
|
13 |
+
def unifint(
|
14 |
+
diff_lb: float,
|
15 |
+
diff_ub: float,
|
16 |
+
bounds: Tuple[int, int]
|
17 |
+
) -> int:
|
18 |
+
"""
|
19 |
+
diff_lb: lower bound for difficulty, must be in range [0, diff_ub]
|
20 |
+
diff_ub: upper bound for difficulty, must be in range [diff_lb, 1]
|
21 |
+
bounds: interval [a, b] determining the integer values that can be sampled
|
22 |
+
"""
|
23 |
+
a, b = bounds
|
24 |
+
d = uniform(diff_lb, diff_ub)
|
25 |
+
global rng
|
26 |
+
rng.append(d)
|
27 |
+
return min(max(a, round(a + (b - a) * d)), b)
|
28 |
+
|
29 |
+
|
30 |
+
def is_grid(
|
31 |
+
grid: Any
|
32 |
+
) -> bool:
|
33 |
+
"""
|
34 |
+
returns True if and only if argument is a valid grid
|
35 |
+
"""
|
36 |
+
if not isinstance(grid, tuple):
|
37 |
+
return False
|
38 |
+
if not 0 < len(grid) <= 30:
|
39 |
+
return False
|
40 |
+
if not all(isinstance(r, tuple) for r in grid):
|
41 |
+
return False
|
42 |
+
if not all(0 < len(r) <= 30 for r in grid):
|
43 |
+
return False
|
44 |
+
if not len(set(len(r) for r in grid)) == 1:
|
45 |
+
return False
|
46 |
+
if not all(all(isinstance(x, int) for x in r) for r in grid):
|
47 |
+
return False
|
48 |
+
if not all(all(0 <= x <= 9 for x in r) for r in grid):
|
49 |
+
return False
|
50 |
+
return True
|
51 |
+
|
52 |
+
|
53 |
+
def strip_prefix(
|
54 |
+
string: str,
|
55 |
+
prefix: str
|
56 |
+
) -> str:
|
57 |
+
"""
|
58 |
+
removes prefix
|
59 |
+
"""
|
60 |
+
return string[len(prefix):]
|
61 |
+
|
62 |
+
|
63 |
+
def format_grid(
|
64 |
+
grid: List[List[int]]
|
65 |
+
) -> Grid:
|
66 |
+
"""
|
67 |
+
grid type casting
|
68 |
+
"""
|
69 |
+
return tuple(tuple(row) for row in grid)
|
70 |
+
|
71 |
+
|
72 |
+
def format_example(
|
73 |
+
example: dict
|
74 |
+
) -> dict:
|
75 |
+
"""
|
76 |
+
example data type
|
77 |
+
"""
|
78 |
+
return {
|
79 |
+
'input': format_grid(example['input']),
|
80 |
+
'output': format_grid(example['output'])
|
81 |
+
}
|
82 |
+
|
83 |
+
|
84 |
+
def format_task(
|
85 |
+
task: dict
|
86 |
+
) -> dict:
|
87 |
+
"""
|
88 |
+
task data type
|
89 |
+
"""
|
90 |
+
return {
|
91 |
+
'train': [format_example(example) for example in task['train']],
|
92 |
+
'test': [format_example(example) for example in task['test']]
|
93 |
+
}
|
94 |
+
|
95 |
+
|
96 |
+
def plot_task(
|
97 |
+
task: List[dict],
|
98 |
+
title: str = None
|
99 |
+
) -> None:
|
100 |
+
"""
|
101 |
+
displays a task
|
102 |
+
"""
|
103 |
+
cmap = ListedColormap([
|
104 |
+
'#000', '#0074D9', '#FF4136', '#2ECC40', '#FFDC00',
|
105 |
+
'#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25'
|
106 |
+
])
|
107 |
+
norm = Normalize(vmin=0, vmax=9)
|
108 |
+
args = {'cmap': cmap, 'norm': norm}
|
109 |
+
height = 2
|
110 |
+
width = len(task)
|
111 |
+
figure_size = (width * 3, height * 3)
|
112 |
+
figure, axes = plt.subplots(height, width, figsize=figure_size)
|
113 |
+
for column, example in enumerate(task):
|
114 |
+
axes[0, column].imshow(example['input'], **args)
|
115 |
+
axes[1, column].imshow(example['output'], **args)
|
116 |
+
axes[0, column].axis('off')
|
117 |
+
axes[1, column].axis('off')
|
118 |
+
if title is not None:
|
119 |
+
figure.suptitle(title, fontsize=20)
|
120 |
+
plt.subplots_adjust(wspace=0.1, hspace=0.1)
|
121 |
+
plt.show()
|
122 |
+
|
123 |
+
|
124 |
+
def fix_bugs(
|
125 |
+
dataset: dict
|
126 |
+
) -> None:
|
127 |
+
"""
|
128 |
+
fixes bugs in the original ARC training dataset
|
129 |
+
"""
|
130 |
+
dataset['a8d7556c']['train'][2]['output'] = fill(dataset['a8d7556c']['train'][2]['output'], 2, {(8, 12), (9, 12)})
|
131 |
+
dataset['6cf79266']['train'][2]['output'] = fill(dataset['6cf79266']['train'][2]['output'], 1, {(6, 17), (7, 17), (8, 15), (8, 16), (8, 17)})
|
132 |
+
dataset['469497ad']['train'][1]['output'] = fill(dataset['469497ad']['train'][1]['output'], 7, {(5, 12), (5, 13), (5, 14)})
|
133 |
+
dataset['9edfc990']['train'][1]['output'] = fill(dataset['9edfc990']['train'][1]['output'], 1, {(6, 13)})
|
134 |
+
dataset['e5062a87']['train'][1]['output'] = fill(dataset['e5062a87']['train'][1]['output'], 2, {(1, 3), (1, 4), (1, 5), (1, 6)})
|
135 |
+
dataset['e5062a87']['train'][0]['output'] = fill(dataset['e5062a87']['train'][0]['output'], 2, {(5, 2), (6, 3), (3, 6), (4, 7)})
|
concept--main/visualization.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import numpy as np
|
3 |
+
from graphviz import Digraph
|
4 |
+
import os
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
import matplotlib.colors as colors
|
7 |
+
|
8 |
+
#Note
|
9 |
+
"visualization functions"
|
10 |
+
|
11 |
+
|
12 |
+
def execute_program(program, input_grid) :
|
13 |
+
return program.evaluate(input_grid)
|
14 |
+
|
15 |
+
def save_tree_as_dot(program, filename):
|
16 |
+
dot = Digraph(comment='Program Tree')
|
17 |
+
def add_nodes_edges(node):
|
18 |
+
if node.children:
|
19 |
+
node_label = f"{node.value}\nID:{node.id}"
|
20 |
+
dot.node(str(node.id), node_label, shape='box', style='filled', color='lightblue')
|
21 |
+
else:
|
22 |
+
node_label = f"{node.value}\nID:{node.id}"
|
23 |
+
dot.node(str(node.id), node_label, shape='ellipse', style='filled', color='lightgreen')
|
24 |
+
|
25 |
+
for child in node.children:
|
26 |
+
dot.edge(str(node.id), str(child.id))
|
27 |
+
add_nodes_edges(child)
|
28 |
+
|
29 |
+
add_nodes_edges(program)
|
30 |
+
dot.render(filename, view=False, format='png')
|
31 |
+
print(f"Program tree saved as {filename}.png")
|
32 |
+
|
33 |
+
def generate_composite_dot(all_generations, filename):
|
34 |
+
dot = Digraph(comment='All Programs Across Generations', graph_attr={'compound': 'true', 'rankdir': 'TB'})
|
35 |
+
dot.attr(rankdir='TB')
|
36 |
+
for gen_idx, generation in enumerate(all_generations):
|
37 |
+
with dot.subgraph(name=f'cluster_gen_{gen_idx}') as c:
|
38 |
+
c.attr(label=f'Generation {gen_idx}')
|
39 |
+
c.attr(style='filled', color='lightgrey')
|
40 |
+
c.attr(rank='same')
|
41 |
+
for prog_idx, (program, fitness) in enumerate(generation.programs_with_fitness):
|
42 |
+
is_selected = program in generation.selected_programs
|
43 |
+
is_best = program == generation.best_program
|
44 |
+
if is_best:
|
45 |
+
node_color = 'gold'
|
46 |
+
node_shape = 'doublecircle'
|
47 |
+
elif is_selected:
|
48 |
+
node_color = 'orange'
|
49 |
+
node_shape = 'box'
|
50 |
+
else:
|
51 |
+
node_color = 'lightblue'
|
52 |
+
node_shape = 'ellipse'
|
53 |
+
def add_nodes_edges(node, parent_id: str = None):
|
54 |
+
label = f"{node.value}\nID:{node.id}"
|
55 |
+
dot.node(str(node.id), label, shape=node_shape, style='filled', color=node_color)
|
56 |
+
if parent_id:
|
57 |
+
dot.edge(parent_id, str(node.id))
|
58 |
+
for child in node.children:
|
59 |
+
add_nodes_edges(child, str(node.id))
|
60 |
+
add_nodes_edges(program)
|
61 |
+
output_path = dot.render(filename, view=False, format='png')
|
62 |
+
print(f"All programs across generations saved as {output_path}")
|
63 |
+
|
64 |
+
# Visualization Functions
|
65 |
+
def plot_comparison(input_grid, expected_output, predicted_output, task_number):
|
66 |
+
fig, axs = plt.subplots(1, 3, figsize=(12, 4))
|
67 |
+
fig.suptitle(f'Task {task_number}')
|
68 |
+
cmap = colors.ListedColormap(['#000000', '#0074D9', '#FF4136', '#2ECC40', '#FFDC00', '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25'])
|
69 |
+
norm = colors.Normalize(vmin=0, vmax=9)
|
70 |
+
|
71 |
+
axs[0].imshow(input_grid, cmap=cmap, norm=norm)
|
72 |
+
axs[0].set_title("Input Grid")
|
73 |
+
axs[1].imshow(expected_output, cmap=cmap, norm=norm)
|
74 |
+
axs[1].set_title("Expected Output")
|
75 |
+
axs[2].imshow(predicted_output, cmap=cmap, norm=norm)
|
76 |
+
axs[2].set_title("Predicted Output")
|
77 |
+
|
78 |
+
plt.tight_layout()
|
79 |
+
plt.show()
|
80 |
+
|
81 |
+
|
82 |
+
|
extr.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
print("hello")
|