Custom collate function that handles kNN data processing directly Args: batch: The batch of data knn_dstore: The KNN datastore vocab_size: Size of the vocabulary device: The device to move tensors to (accelerator.device)
(batch, knn_dstore, vocab_size)
| 426 | knn_dstore.set_format(type='torch', columns=['id_cnt', 'token_id', 'prob', 'label']) |
| 427 | |
| 428 | def knn_collate_fn(batch, knn_dstore, vocab_size): |
| 429 | """ |
| 430 | Custom collate function that handles kNN data processing directly |
| 431 | |
| 432 | Args: |
| 433 | batch: The batch of data |
| 434 | knn_dstore: The KNN datastore |
| 435 | vocab_size: Size of the vocabulary |
| 436 | device: The device to move tensors to (accelerator.device) |
| 437 | """ |
| 438 | # Apply default collation to the batch |
| 439 | collated_batch = default_data_collator(batch) |
| 440 | |
| 441 | # Process kNN data for all items in the batch |
| 442 | knn_labels_list = [] |
| 443 | knn_probs_list = [] |
| 444 | |
| 445 | # Process each dstore_range in the batch |
| 446 | for idx, cur_range in enumerate(collated_batch["dstore_range"]): |
| 447 | # Get range boundaries |
| 448 | start, end = int(cur_range[0]), int(cur_range[1]) |
| 449 | |
| 450 | # Slice the knn_dstore |
| 451 | knn_dstore_slice = knn_dstore.select(range(start, end)) |
| 452 | |
| 453 | # Extract kNN label |
| 454 | # Note that since datasets version 4.0.0, we can't use direct column selecting since the implementation of lazy columns, see pr https://github.com/huggingface/datasets/pull/7614 |
| 455 | cur_knn_label = knn_dstore_slice[:]["label"] |
| 456 | knn_labels_list.append(cur_knn_label) |
| 457 | |
| 458 | # Extract token IDs and probabilities |
| 459 | cur_token_id = knn_dstore_slice[:]["token_id"] |
| 460 | cur_prob = knn_dstore_slice[:]["prob"] |
| 461 | |
| 462 | # Create sparse probability tensor |
| 463 | cur_knn_prob = torch.zeros(size=(end - start, vocab_size)) |
| 464 | for i in range(end - start): |
| 465 | assert cur_token_id[i].max() < vocab_size, f"token_id {cur_token_id[i]} is out of vocab size {vocab_size}" |
| 466 | cur_knn_prob[i][cur_token_id[i]] = cur_prob[i] |
| 467 | |
| 468 | knn_probs_list.append(cur_knn_prob) |
| 469 | |
| 470 | # Concatenate and move to device |
| 471 | collated_batch["knn_label"] = torch.cat(knn_labels_list, dim=0) |
| 472 | collated_batch["knn_probs"] = torch.cat(knn_probs_list, dim=0) |
| 473 | |
| 474 | return collated_batch |
| 475 | |
| 476 | # --------------------------------------------------Evaluation----------------------------------------------------------- |
| 477 | if args.do_test: |
nothing calls this directly
no outgoing calls
no test coverage detected