zirobtc commited on
Commit
6c6e811
·
verified ·
1 Parent(s): d07e737

Upload get_text_embeedings.py

Browse files
Files changed (1) hide show
  1. get_text_embeedings.py +113 -0
get_text_embeedings.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pre-computes T5 text embeddings for the MotionStreamer dataset.
3
+ This script is GUARANTEED to be correct because it imports the
4
+ original base Text2MotionDataset class and scans its internal 'data_dict'
5
+ to discover every possible caption, including all sub-clips.
6
+ """
7
+ import os
8
+ import torch
9
+ import numpy as np
10
+ from sentence_transformers import SentenceTransformer
11
+ from tqdm import tqdm
12
+ import argparse
13
+ import hashlib
14
+ import json
15
+ import sys
16
+
17
+ # --- CRITICAL: Import the actual dataset class from your project ---
18
+ try:
19
+ from humanml3d_272.dataset_TM_train_motionstreamer import Text2MotionDataset
20
+ except ImportError as e:
21
+ print("FATAL ERROR: Could not import the 'Text2MotionDataset' class.")
22
+ print("Please make sure you run this script from the root of your project directory.")
23
+ print(f"Original error: {e}")
24
+ sys.exit(1)
25
+
26
+ def get_args_parser():
27
+ parser = argparse.ArgumentParser(description='Pre-compute T5 Embeddings')
28
+
29
+ # --- Args needed for the Text2MotionDataset ---
30
+ # These must match the values your dataloader uses
31
+ parser.add_argument('--dataname', type=str, default='t2m_babel_272', help='Dataset name (for dataset init)')
32
+ parser.add_argument('--latent_dir', type=str, default='babel_272_stream/t2m_babel_latents', help='Latent dir (for dataset init)')
33
+ parser.add_argument('--unit_length', type=int, default=4, help='Unit length (for dataset init, 4 is a common default)')
34
+
35
+ # --- Args for this script ---
36
+ parser.add_argument('--output_file', type=str, default='babel_272_stream/text_embeddings.npy', help='Path to save the output .npy file.')
37
+ parser.add_argument('--t5_model_path', type=str, default='sentence-t5-xl', help='Path or HF name for the Sentence-T5-XL model')
38
+ parser.add_argument('--batch_size', type=int, default=256, help='Batch size for T5 encoding.')
39
+ return parser
40
+
41
+ def main():
42
+ parser = get_args_parser()
43
+ args = parser.parse_args()
44
+ print(f"Configuration:\n{json.dumps(vars(args), indent=4, sort_keys=True)}")
45
+
46
+ output_dir = os.path.dirname(args.output_file)
47
+ os.makedirs(output_dir, exist_ok=True)
48
+ print(f"Embeddings will be saved to: {args.output_file}")
49
+
50
+ # Load T5 model
51
+ print(f"Loading T5 model from: {args.t5_model_path}")
52
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
53
+
54
+ if device == 'cuda' and torch.cuda.is_bf16_supported():
55
+ print("bfloat16 is supported, loading model in bf16.")
56
+ t5_model = SentenceTransformer(args.t5_model_path, device=device, model_kwargs={'torch_dtype': torch.bfloat16})
57
+ else:
58
+ print("bfloat16 not supported or not on CUDA, loading model in fp32.")
59
+ t5_model = SentenceTransformer(args.t5_model_path, device=device)
60
+ t5_model.eval()
61
+ for p in t5_model.parameters():
62
+ p.requires_grad = False
63
+ print("T5 model loaded successfully.")
64
+
65
+ # --- THIS IS THE CORRECT LOGIC (FROM YOUR OLD SCRIPT) ---
66
+ print("Instantiating the Text2MotionDataset to scan for all captions...")
67
+ dataset = Text2MotionDataset(
68
+ dataset_name=args.dataname,
69
+ latent_dir=args.latent_dir,
70
+ unit_length=args.unit_length
71
+ )
72
+
73
+ if not hasattr(dataset, 'data_dict') or not isinstance(dataset.data_dict, dict):
74
+ print("FATAL ERROR: The imported Text2MotionDataset does not have 'data_dict'.")
75
+ sys.exit(1)
76
+
77
+ unique_captions = set()
78
+ unique_captions.add('') # Add the unconditional caption for 10% dropout
79
+ print("Extracting all unique captions from the dataset's internal dictionary...")
80
+
81
+ for data_item in tqdm(dataset.data_dict.values(), desc="Scanning discovered samples"):
82
+ for text_dict in data_item['text']:
83
+ unique_captions.add(text_dict['caption'])
84
+
85
+ captions_list = list(unique_captions)
86
+ print(f"Found {len(captions_list)} unique captions to encode.")
87
+ # --- END CORRECT LOGIC ---
88
+
89
+ print(f"Encoding {len(captions_list)} captions in batches of {args.batch_size}...")
90
+ with torch.no_grad():
91
+ all_embeddings = t5_model.encode(
92
+ captions_list,
93
+ batch_size=args.batch_size,
94
+ convert_to_tensor=True,
95
+ show_progress_bar=True
96
+ )
97
+
98
+ all_embeddings_fp32 = all_embeddings.to(torch.float32).cpu().numpy()
99
+
100
+ # Populate the dictionary
101
+ embeddings_dict = {}
102
+ for i, final_caption in enumerate(captions_list):
103
+ # Use sha256 to match the hash your *new* script was trying to use
104
+ caption_hash = hashlib.sha256(final_caption.encode('utf-8')).hexdigest()
105
+ embeddings_dict[caption_hash] = all_embeddings_fp32[i]
106
+
107
+ print(f"Saving {len(embeddings_dict)} embeddings to {args.output_file}...")
108
+ np.save(args.output_file, embeddings_dict, allow_pickle=True)
109
+
110
+ print("--- All text embeddings have been pre-computed and saved. ---")
111
+
112
+ if __name__ == '__main__':
113
+ main()