tf-models-nightly 2.19.0.dev20250108__py2.py3-none-any.whl → 2.19.0.dev20250110__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of tf-models-nightly might be problematic. Click here for more details.

Files changed (32) hide show
  1. official/projects/detr/__init__.py +14 -0
  2. official/projects/detr/configs/__init__.py +14 -0
  3. official/projects/detr/configs/detr.py +277 -0
  4. official/projects/detr/configs/detr_test.py +51 -0
  5. official/projects/detr/dataloaders/__init__.py +14 -0
  6. official/projects/detr/dataloaders/coco.py +157 -0
  7. official/projects/detr/dataloaders/coco_test.py +111 -0
  8. official/projects/detr/dataloaders/detr_input.py +175 -0
  9. official/projects/detr/experiments/__init__.py +14 -0
  10. official/projects/detr/modeling/__init__.py +14 -0
  11. official/projects/detr/modeling/detr.py +345 -0
  12. official/projects/detr/modeling/detr_test.py +70 -0
  13. official/projects/detr/modeling/transformer.py +849 -0
  14. official/projects/detr/modeling/transformer_test.py +263 -0
  15. official/projects/detr/ops/__init__.py +14 -0
  16. official/projects/detr/ops/matchers.py +489 -0
  17. official/projects/detr/ops/matchers_test.py +95 -0
  18. official/projects/detr/optimization.py +151 -0
  19. official/projects/detr/serving/__init__.py +14 -0
  20. official/projects/detr/serving/export_module.py +103 -0
  21. official/projects/detr/serving/export_module_test.py +98 -0
  22. official/projects/detr/serving/export_saved_model.py +109 -0
  23. official/projects/detr/tasks/__init__.py +14 -0
  24. official/projects/detr/tasks/detection.py +421 -0
  25. official/projects/detr/tasks/detection_test.py +203 -0
  26. official/projects/detr/train.py +70 -0
  27. {tf_models_nightly-2.19.0.dev20250108.dist-info → tf_models_nightly-2.19.0.dev20250110.dist-info}/METADATA +1 -1
  28. {tf_models_nightly-2.19.0.dev20250108.dist-info → tf_models_nightly-2.19.0.dev20250110.dist-info}/RECORD +32 -6
  29. {tf_models_nightly-2.19.0.dev20250108.dist-info → tf_models_nightly-2.19.0.dev20250110.dist-info}/AUTHORS +0 -0
  30. {tf_models_nightly-2.19.0.dev20250108.dist-info → tf_models_nightly-2.19.0.dev20250110.dist-info}/LICENSE +0 -0
  31. {tf_models_nightly-2.19.0.dev20250108.dist-info → tf_models_nightly-2.19.0.dev20250110.dist-info}/WHEEL +0 -0
  32. {tf_models_nightly-2.19.0.dev20250108.dist-info → tf_models_nightly-2.19.0.dev20250110.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,489 @@
1
+ # Copyright 2024 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Tensorflow implementation to solve the Linear Sum Assignment problem.
16
+
17
+ The Linear Sum Assignment problem involves determining the minimum weight
18
+ matching for bipartite graphs. For example, this problem can be defined by
19
+ a 2D matrix C, where each element i,j determines the cost of matching worker i
20
+ with job j. The solution to the problem is a complete assignment of jobs to
21
+ workers, such that no job is assigned to more than one work and no worker is
22
+ assigned more than one job, with minimum cost.
23
+
24
+ This implementation builds off of the Hungarian
25
+ Matching Algorithm (https://www.cse.ust.hk/~golin/COMP572/Notes/Matching.pdf).
26
+
27
+ Based on the original implementation by Jiquan Ngiam <jngiam@google.com>.
28
+ """
29
+ import tensorflow as tf, tf_keras
30
+ from official.modeling import tf_utils
31
+
32
+
33
+ def _prepare(weights):
34
+ """Prepare the cost matrix.
35
+
36
+ To speed up computational efficiency of the algorithm, all weights are shifted
37
+ to be non-negative. Each element is reduced by the row / column minimum. Note
38
+ that neither operation will effect the resulting solution but will provide
39
+ a better starting point for the greedy assignment. Note this corresponds to
40
+ the pre-processing and step 1 of the Hungarian algorithm from Wikipedia.
41
+
42
+ Args:
43
+ weights: A float32 [batch_size, num_elems, num_elems] tensor, where each
44
+ inner matrix represents weights to be use for matching.
45
+
46
+ Returns:
47
+ A prepared weights tensor of the same shape and dtype.
48
+ """
49
+ # Since every worker needs a job and every job needs a worker, we can subtract
50
+ # the minimum from each.
51
+ weights -= tf.reduce_min(weights, axis=2, keepdims=True)
52
+ weights -= tf.reduce_min(weights, axis=1, keepdims=True)
53
+ return weights
54
+
55
+
56
+ def _greedy_assignment(adj_matrix):
57
+ """Greedily assigns workers to jobs based on an adjaceny matrix.
58
+
59
+ Starting with an adjacency matrix representing the available connections
60
+ in the bi-partite graph, this function greedily chooses elements such
61
+ that each worker is matched to at most one job (or each job is assigned to
62
+ at most one worker). Note, if the adjacency matrix has no available values
63
+ for a particular row/column, the corresponding job/worker may go unassigned.
64
+
65
+ Args:
66
+ adj_matrix: A bool [batch_size, num_elems, num_elems] tensor, where each
67
+ element of the inner matrix represents whether the worker (row) can be
68
+ matched to the job (column).
69
+
70
+ Returns:
71
+ A bool [batch_size, num_elems, num_elems] tensor, where each element of the
72
+ inner matrix represents whether the worker has been matched to the job.
73
+ Each row and column can have at most one true element. Some of the rows
74
+ and columns may not be matched.
75
+ """
76
+ _, num_elems, _ = tf_utils.get_shape_list(adj_matrix, expected_rank=3)
77
+ adj_matrix = tf.transpose(adj_matrix, [1, 0, 2])
78
+
79
+ # Create a dynamic TensorArray containing the assignments for each worker/job
80
+ assignment = tf.TensorArray(tf.bool, num_elems)
81
+
82
+ # Store the elements assigned to each column to update each iteration
83
+ col_assigned = tf.zeros_like(adj_matrix[0, ...], dtype=tf.bool)
84
+
85
+ # Iteratively assign each row using tf.foldl. Intuitively, this is a loop
86
+ # over rows, where we incrementally assign each row.
87
+ def _assign_row(accumulator, row_adj):
88
+ # The accumulator tracks the row assignment index.
89
+ idx, assignment, col_assigned = accumulator
90
+
91
+ # Viable candidates cannot already be assigned to another job.
92
+ candidates = row_adj & (~col_assigned)
93
+
94
+ # Deterministically assign to the candidates of the highest index count.
95
+ max_candidate_idx = tf.argmax(
96
+ tf.cast(candidates, tf.int32), axis=1, output_type=tf.int32)
97
+
98
+ candidates_indicator = tf.one_hot(
99
+ max_candidate_idx,
100
+ num_elems,
101
+ on_value=True,
102
+ off_value=False,
103
+ dtype=tf.bool)
104
+ candidates_indicator &= candidates
105
+
106
+ # Make assignment to the column.
107
+ col_assigned |= candidates_indicator
108
+ assignment = assignment.write(idx, candidates_indicator)
109
+
110
+ return (idx + 1, assignment, col_assigned)
111
+
112
+ _, assignment, _ = tf.foldl(
113
+ _assign_row, adj_matrix, (0, assignment, col_assigned), back_prop=False)
114
+
115
+ assignment = assignment.stack()
116
+ assignment = tf.transpose(assignment, [1, 0, 2])
117
+ return assignment
118
+
119
+
120
+ def _find_augmenting_path(assignment, adj_matrix):
121
+ """Finds an augmenting path given an assignment and an adjacency matrix.
122
+
123
+ The augmenting path search starts from the unassigned workers, then goes on
124
+ to find jobs (via an unassigned pairing), then back again to workers (via an
125
+ existing pairing), and so on. The path alternates between unassigned and
126
+ existing pairings. Returns the state after the search.
127
+
128
+ Note: In the state the worker and job, indices are 1-indexed so that we can
129
+ use 0 to represent unreachable nodes. State contains the following keys:
130
+
131
+ - jobs: A [batch_size, 1, num_elems] tensor containing the highest index
132
+ unassigned worker that can reach this job through a path.
133
+ - jobs_from_worker: A [batch_size, num_elems] tensor containing the worker
134
+ reached immediately before this job.
135
+ - workers: A [batch_size, num_elems, 1] tensor containing the highest index
136
+ unassigned worker that can reach this worker through a path.
137
+ - workers_from_job: A [batch_size, num_elems] tensor containing the job
138
+ reached immediately before this worker.
139
+ - new_jobs: A bool [batch_size, num_elems] tensor containing True if the
140
+ unassigned job can be reached via a path.
141
+
142
+ State can be used to recover the path via backtracking.
143
+
144
+ Args:
145
+ assignment: A bool [batch_size, num_elems, num_elems] tensor, where each
146
+ element of the inner matrix represents whether the worker has been matched
147
+ to the job. This may be a partial assignment.
148
+ adj_matrix: A bool [batch_size, num_elems, num_elems] tensor, where each
149
+ element of the inner matrix represents whether the worker (row) can be
150
+ matched to the job (column).
151
+
152
+ Returns:
153
+ A state dict, which represents the outcome of running an augmenting
154
+ path search on the graph given the assignment.
155
+ """
156
+ batch_size, num_elems, _ = tf_utils.get_shape_list(
157
+ assignment, expected_rank=3)
158
+ unassigned_workers = ~tf.reduce_any(assignment, axis=2, keepdims=True)
159
+ unassigned_jobs = ~tf.reduce_any(assignment, axis=1, keepdims=True)
160
+
161
+ unassigned_pairings = tf.cast(adj_matrix & ~assignment, tf.int32)
162
+ existing_pairings = tf.cast(assignment, tf.int32)
163
+
164
+ # Initialize unassigned workers to have non-zero ids, assigned workers will
165
+ # have ids = 0.
166
+ worker_indices = tf.range(1, num_elems + 1, dtype=tf.int32)
167
+ init_workers = tf.tile(worker_indices[tf.newaxis, :, tf.newaxis],
168
+ [batch_size, 1, 1])
169
+ init_workers *= tf.cast(unassigned_workers, tf.int32)
170
+
171
+ state = {
172
+ "jobs": tf.zeros((batch_size, 1, num_elems), dtype=tf.int32),
173
+ "jobs_from_worker": tf.zeros((batch_size, num_elems), dtype=tf.int32),
174
+ "workers": init_workers,
175
+ "workers_from_job": tf.zeros((batch_size, num_elems), dtype=tf.int32)
176
+ }
177
+
178
+ def _has_active_workers(state, curr_workers):
179
+ """Check if there are still active workers."""
180
+ del state
181
+ return tf.reduce_sum(curr_workers) > 0
182
+
183
+ def _augment_step(state, curr_workers):
184
+ """Performs one search step."""
185
+
186
+ # Note: These steps could be potentially much faster if sparse matrices are
187
+ # supported. The unassigned_pairings and existing_pairings matrices can be
188
+ # very sparse.
189
+
190
+ # Find potential jobs using current workers.
191
+ potential_jobs = curr_workers * unassigned_pairings
192
+ curr_jobs = tf.reduce_max(potential_jobs, axis=1, keepdims=True)
193
+ curr_jobs_from_worker = 1 + tf.argmax(
194
+ potential_jobs, axis=1, output_type=tf.int32)
195
+
196
+ # Remove already accessible jobs from curr_jobs.
197
+ default_jobs = tf.zeros_like(state["jobs"], dtype=state["jobs"].dtype)
198
+ curr_jobs = tf.where(state["jobs"] > 0, default_jobs, curr_jobs)
199
+ curr_jobs_from_worker *= tf.cast(curr_jobs > 0, tf.int32)[:, 0, :]
200
+
201
+ # Find potential workers from current jobs.
202
+ potential_workers = curr_jobs * existing_pairings
203
+ curr_workers = tf.reduce_max(potential_workers, axis=2, keepdims=True)
204
+ curr_workers_from_job = 1 + tf.argmax(
205
+ potential_workers, axis=2, output_type=tf.int32)
206
+
207
+ # Remove already accessible workers from curr_workers.
208
+ default_workers = tf.zeros_like(state["workers"])
209
+ curr_workers = tf.where(
210
+ state["workers"] > 0, default_workers, curr_workers)
211
+ curr_workers_from_job *= tf.cast(curr_workers > 0, tf.int32)[:, :, 0]
212
+
213
+ # Update state so that we can backtrack later.
214
+ state = state.copy()
215
+ state["jobs"] = tf.maximum(state["jobs"], curr_jobs)
216
+ state["jobs_from_worker"] = tf.maximum(state["jobs_from_worker"],
217
+ curr_jobs_from_worker)
218
+ state["workers"] = tf.maximum(state["workers"], curr_workers)
219
+ state["workers_from_job"] = tf.maximum(state["workers_from_job"],
220
+ curr_workers_from_job)
221
+
222
+ return state, curr_workers
223
+
224
+ state, _ = tf.while_loop(
225
+ _has_active_workers,
226
+ _augment_step, (state, init_workers),
227
+ back_prop=False)
228
+
229
+ # Compute new jobs, this is useful for determnining termnination of the
230
+ # maximum bi-partite matching and initialization for backtracking.
231
+ new_jobs = (state["jobs"] > 0) & unassigned_jobs
232
+ state["new_jobs"] = new_jobs[:, 0, :]
233
+ return state
234
+
235
+
236
+ def _improve_assignment(assignment, state):
237
+ """Improves an assignment by backtracking the augmented path using state.
238
+
239
+ Args:
240
+ assignment: A bool [batch_size, num_elems, num_elems] tensor, where each
241
+ element of the inner matrix represents whether the worker has been matched
242
+ to the job. This may be a partial assignment.
243
+ state: A dict, which represents the outcome of running an augmenting path
244
+ search on the graph given the assignment.
245
+
246
+ Returns:
247
+ A new assignment matrix of the same shape and type as assignment, where the
248
+ assignment has been updated using the augmented path found.
249
+ """
250
+ batch_size, num_elems, _ = tf_utils.get_shape_list(assignment, 3)
251
+
252
+ # We store the current job id and iteratively backtrack using jobs_from_worker
253
+ # and workers_from_job until we reach an unassigned worker. We flip all the
254
+ # assignments on this path to discover a better overall assignment.
255
+
256
+ # Note: The indices in state are 1-indexed, where 0 represents that the
257
+ # worker / job cannot be reached.
258
+
259
+ # Obtain initial job indices based on new_jobs.
260
+ curr_job_idx = tf.argmax(
261
+ tf.cast(state["new_jobs"], tf.int32), axis=1, output_type=tf.int32)
262
+
263
+ # Track whether an example is actively being backtracked. Since we are
264
+ # operating on a batch, not all examples in the batch may be active.
265
+ active = tf.gather(state["new_jobs"], curr_job_idx, batch_dims=1)
266
+ batch_range = tf.range(0, batch_size, dtype=tf.int32)
267
+
268
+ # Flip matrix tracks which assignments we need to flip - corresponding to the
269
+ # augmenting path taken. We use an integer tensor here so that we can use
270
+ # tensor_scatter_nd_add to update the tensor, and then cast it back to bool
271
+ # after the loop.
272
+ flip_matrix = tf.zeros((batch_size, num_elems, num_elems), dtype=tf.int32)
273
+
274
+ def _has_active_backtracks(flip_matrix, active, curr_job_idx):
275
+ """Check if there are still active workers."""
276
+ del flip_matrix, curr_job_idx
277
+ return tf.reduce_any(active)
278
+
279
+ def _backtrack_one_step(flip_matrix, active, curr_job_idx):
280
+ """Take one step in backtracking."""
281
+ # Discover the worker that the job originated from, note that this worker
282
+ # must exist by construction.
283
+ curr_worker_idx = tf.gather(
284
+ state["jobs_from_worker"], curr_job_idx, batch_dims=1) - 1
285
+ curr_worker_idx = tf.maximum(curr_worker_idx, 0)
286
+ update_indices = tf.stack([batch_range, curr_worker_idx, curr_job_idx],
287
+ axis=1)
288
+ update_indices = tf.maximum(update_indices, 0)
289
+ flip_matrix = tf.tensor_scatter_nd_add(flip_matrix, update_indices,
290
+ tf.cast(active, tf.int32))
291
+
292
+ # Discover the (potential) job that the worker originated from.
293
+ curr_job_idx = tf.gather(
294
+ state["workers_from_job"], curr_worker_idx, batch_dims=1) - 1
295
+ # Note that jobs may not be active, and we track that here (before
296
+ # adjusting indices so that they are all >= 0 for gather).
297
+ active &= curr_job_idx >= 0
298
+ curr_job_idx = tf.maximum(curr_job_idx, 0)
299
+ update_indices = tf.stack([batch_range, curr_worker_idx, curr_job_idx],
300
+ axis=1)
301
+ update_indices = tf.maximum(update_indices, 0)
302
+ flip_matrix = tf.tensor_scatter_nd_add(flip_matrix, update_indices,
303
+ tf.cast(active, tf.int32))
304
+
305
+ return flip_matrix, active, curr_job_idx
306
+
307
+ flip_matrix, _, _ = tf.while_loop(
308
+ _has_active_backtracks,
309
+ _backtrack_one_step, (flip_matrix, active, curr_job_idx),
310
+ back_prop=False)
311
+
312
+ flip_matrix = tf.cast(flip_matrix, tf.bool)
313
+ assignment = tf.math.logical_xor(assignment, flip_matrix)
314
+
315
+ return assignment
316
+
317
+
318
+ def _maximum_bipartite_matching(adj_matrix, assignment=None):
319
+ """Performs maximum bipartite matching using augmented paths.
320
+
321
+ Args:
322
+ adj_matrix: A bool [batch_size, num_elems, num_elems] tensor, where each
323
+ element of the inner matrix represents whether the worker (row) can be
324
+ matched to the job (column).
325
+ assignment: An optional bool [batch_size, num_elems, num_elems] tensor,
326
+ where each element of the inner matrix represents whether the worker has
327
+ been matched to the job. This may be a partial assignment. If specified,
328
+ this assignment will be used to seed the iterative algorithm.
329
+
330
+ Returns:
331
+ A state dict representing the final augmenting path state search, and
332
+ a maximum bipartite matching assignment tensor. Note that the state outcome
333
+ can be used to compute a minimum vertex cover for the bipartite graph.
334
+ """
335
+
336
+ if assignment is None:
337
+ assignment = _greedy_assignment(adj_matrix)
338
+
339
+ state = _find_augmenting_path(assignment, adj_matrix)
340
+
341
+ def _has_new_jobs(state, assignment):
342
+ del assignment
343
+ return tf.reduce_any(state["new_jobs"])
344
+
345
+ def _improve_assignment_and_find_new_path(state, assignment):
346
+ assignment = _improve_assignment(assignment, state)
347
+ state = _find_augmenting_path(assignment, adj_matrix)
348
+ return state, assignment
349
+
350
+ state, assignment = tf.while_loop(
351
+ _has_new_jobs,
352
+ _improve_assignment_and_find_new_path, (state, assignment),
353
+ back_prop=False)
354
+
355
+ return state, assignment
356
+
357
+
358
+ def _compute_cover(state, assignment):
359
+ """Computes a cover for the bipartite graph.
360
+
361
+ We compute a cover using the construction provided at
362
+ https://en.wikipedia.org/wiki/K%C5%91nig%27s_theorem_(graph_theory)#Proof
363
+ which uses the outcome from the alternating path search.
364
+
365
+ Args:
366
+ state: A state dict, which represents the outcome of running an augmenting
367
+ path search on the graph given the assignment.
368
+ assignment: An optional bool [batch_size, num_elems, num_elems] tensor,
369
+ where each element of the inner matrix represents whether the worker has
370
+ been matched to the job. This may be a partial assignment. If specified,
371
+ this assignment will be used to seed the iterative algorithm.
372
+
373
+ Returns:
374
+ A tuple of (workers_cover, jobs_cover) corresponding to row and column
375
+ covers for the bipartite graph. workers_cover is a boolean tensor of shape
376
+ [batch_size, num_elems, 1] and jobs_cover is a boolean tensor of shape
377
+ [batch_size, 1, num_elems].
378
+ """
379
+ assigned_workers = tf.reduce_any(assignment, axis=2, keepdims=True)
380
+ assigned_jobs = tf.reduce_any(assignment, axis=1, keepdims=True)
381
+
382
+ reachable_workers = state["workers"] > 0
383
+ reachable_jobs = state["jobs"] > 0
384
+
385
+ workers_cover = assigned_workers & (~reachable_workers)
386
+ jobs_cover = assigned_jobs & reachable_jobs
387
+
388
+ return workers_cover, jobs_cover
389
+
390
+
391
+ def _update_weights_using_cover(workers_cover, jobs_cover, weights):
392
+ """Updates weights for hungarian matching using a cover.
393
+
394
+ We first find the minimum uncovered weight. Then, we subtract this from all
395
+ the uncovered weights, and add it to all the doubly covered weights.
396
+
397
+ Args:
398
+ workers_cover: A boolean tensor of shape [batch_size, num_elems, 1].
399
+ jobs_cover: A boolean tensor of shape [batch_size, 1, num_elems].
400
+ weights: A float32 [batch_size, num_elems, num_elems] tensor, where each
401
+ inner matrix represents weights to be use for matching.
402
+
403
+ Returns:
404
+ A new weight matrix with elements adjusted by the cover.
405
+ """
406
+ max_value = tf.reduce_max(weights)
407
+
408
+ covered = workers_cover | jobs_cover
409
+ double_covered = workers_cover & jobs_cover
410
+
411
+ uncovered_weights = tf.where(covered,
412
+ tf.ones_like(weights) * max_value, weights)
413
+ min_weight = tf.reduce_min(uncovered_weights, axis=[-2, -1], keepdims=True)
414
+
415
+ add_weight = tf.where(double_covered,
416
+ tf.ones_like(weights) * min_weight,
417
+ tf.zeros_like(weights))
418
+ sub_weight = tf.where(covered, tf.zeros_like(weights),
419
+ tf.ones_like(weights) * min_weight)
420
+
421
+ return weights + add_weight - sub_weight
422
+
423
+
424
+ def assert_rank(tensor, expected_rank, name=None):
425
+ """Raises an exception if the tensor rank is not of the expected rank.
426
+
427
+ Args:
428
+ tensor: A tf.Tensor to check the rank of.
429
+ expected_rank: Python integer or list of integers, expected rank.
430
+ name: Optional name of the tensor for the error message.
431
+
432
+ Raises:
433
+ ValueError: If the expected shape doesn't match the actual shape.
434
+ """
435
+ expected_rank_dict = {}
436
+ if isinstance(expected_rank, int):
437
+ expected_rank_dict[expected_rank] = True
438
+ else:
439
+ for x in expected_rank:
440
+ expected_rank_dict[x] = True
441
+
442
+ actual_rank = len(tensor.shape)
443
+ if actual_rank not in expected_rank_dict:
444
+ raise ValueError(
445
+ "For the tensor `%s`, the actual tensor rank `%d` (shape = %s) is not "
446
+ "equal to the expected tensor rank `%s`" %
447
+ (name, actual_rank, str(tensor.shape), str(expected_rank)))
448
+
449
+
450
+ def hungarian_matching(weights):
451
+ """Computes the minimum linear sum assignment using the Hungarian algorithm.
452
+
453
+ Args:
454
+ weights: A float32 [batch_size, num_elems, num_elems] tensor, where each
455
+ inner matrix represents weights to be use for matching.
456
+
457
+ Returns:
458
+ A bool [batch_size, num_elems, num_elems] tensor, where each element of the
459
+ inner matrix represents whether the worker has been matched to the job.
460
+ The returned matching will always be a perfect match.
461
+ """
462
+ batch_size, num_elems, _ = tf_utils.get_shape_list(weights, 3)
463
+
464
+ weights = _prepare(weights)
465
+ adj_matrix = tf.equal(weights, 0.)
466
+ state, assignment = _maximum_bipartite_matching(adj_matrix)
467
+ workers_cover, jobs_cover = _compute_cover(state, assignment)
468
+
469
+ def _cover_incomplete(workers_cover, jobs_cover, *args):
470
+ del args
471
+ cover_sum = (
472
+ tf.reduce_sum(tf.cast(workers_cover, tf.int32)) +
473
+ tf.reduce_sum(tf.cast(jobs_cover, tf.int32)))
474
+ return tf.less(cover_sum, batch_size * num_elems)
475
+
476
+ def _update_weights_and_match(workers_cover, jobs_cover, weights, assignment):
477
+ weights = _update_weights_using_cover(workers_cover, jobs_cover, weights)
478
+ adj_matrix = tf.equal(weights, 0.)
479
+ state, assignment = _maximum_bipartite_matching(adj_matrix, assignment)
480
+ workers_cover, jobs_cover = _compute_cover(state, assignment)
481
+ return workers_cover, jobs_cover, weights, assignment
482
+
483
+ workers_cover, jobs_cover, weights, assignment = tf.while_loop(
484
+ _cover_incomplete,
485
+ _update_weights_and_match,
486
+ (workers_cover, jobs_cover, weights, assignment),
487
+ back_prop=False)
488
+ return weights, assignment
489
+
@@ -0,0 +1,95 @@
1
+ # Copyright 2024 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Tests for tensorflow_models.official.projects.detr.ops.matchers."""
16
+
17
+ import numpy as np
18
+ from scipy import optimize
19
+ import tensorflow as tf, tf_keras
20
+
21
+ from official.projects.detr.ops import matchers
22
+
23
+
24
+ class MatchersOpsTest(tf.test.TestCase):
25
+
26
+ def testLinearSumAssignment(self):
27
+ """Check a simple 2D test case of the Linear Sum Assignment problem.
28
+
29
+ Ensures that the implementation of the matching algorithm is correct
30
+ and functional on TPUs.
31
+ """
32
+ cost_matrix = np.array([[[4, 1, 3], [2, 0, 5], [3, 2, 2]]],
33
+ dtype=np.float32)
34
+ _, adjacency_matrix = matchers.hungarian_matching(tf.constant(cost_matrix))
35
+ adjacency_output = adjacency_matrix.numpy()
36
+
37
+ correct_output = np.array([
38
+ [0, 1, 0],
39
+ [1, 0, 0],
40
+ [0, 0, 1],
41
+ ], dtype=bool)
42
+ self.assertAllEqual(adjacency_output[0], correct_output)
43
+
44
+ def testBatchedLinearSumAssignment(self):
45
+ """Check a batched case of the Linear Sum Assignment Problem.
46
+
47
+ Ensures that a correct solution is found for all inputted problems within
48
+ a batch.
49
+ """
50
+ cost_matrix = np.array([
51
+ [[4, 1, 3], [2, 0, 5], [3, 2, 2]],
52
+ [[1, 4, 3], [0, 2, 5], [2, 3, 2]],
53
+ [[1, 3, 4], [0, 5, 2], [2, 2, 3]],
54
+ ],
55
+ dtype=np.float32)
56
+ _, adjacency_matrix = matchers.hungarian_matching(tf.constant(cost_matrix))
57
+ adjacency_output = adjacency_matrix.numpy()
58
+
59
+ # Hand solved correct output for the linear sum assignment problem
60
+ correct_output = np.array([
61
+ [[0, 1, 0], [1, 0, 0], [0, 0, 1]],
62
+ [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
63
+ [[1, 0, 0], [0, 0, 1], [0, 1, 0]],
64
+ ],
65
+ dtype=bool)
66
+ self.assertAllClose(adjacency_output, correct_output)
67
+
68
+ def testMaximumBipartiteMatching(self):
69
+ """Check that the maximum bipartite match assigns the correct numbers."""
70
+ adj_matrix = tf.cast([[
71
+ [1, 0, 0, 0, 1],
72
+ [0, 1, 0, 1, 0],
73
+ [0, 0, 1, 0, 0],
74
+ [0, 1, 0, 0, 0],
75
+ [1, 0, 0, 0, 0],
76
+ ]], tf.bool)
77
+ _, assignment = matchers._maximum_bipartite_matching(adj_matrix)
78
+ self.assertEqual(np.sum(assignment.numpy()), 5)
79
+
80
+ def testAssignmentMatchesScipy(self):
81
+ """Check that the Linear Sum Assignment matches the Scipy implementation."""
82
+ batch_size, num_elems = 2, 25
83
+ weights = tf.random.uniform((batch_size, num_elems, num_elems),
84
+ minval=0.,
85
+ maxval=1.)
86
+ weights, assignment = matchers.hungarian_matching(weights)
87
+
88
+ for idx in range(batch_size):
89
+ _, scipy_assignment = optimize.linear_sum_assignment(weights.numpy()[idx])
90
+ hungarian_assignment = np.where(assignment.numpy()[idx])[1]
91
+
92
+ self.assertAllEqual(hungarian_assignment, scipy_assignment)
93
+
94
+ if __name__ == '__main__':
95
+ tf.test.main()