Neptune-T commited on
Commit
5bdb926
·
verified ·
1 Parent(s): e42d392

Add files using upload-large-folder tool

Browse files
DragMesh/dragmesh/data/balanced_dataset_utils.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: utils/balanced_dataset_utils.py
3
+ Utilities for building/reading LMDB datasets and computing balanced sampling weights.
4
+ """
5
+ import os
6
+ import torch
7
+ import numpy as np
8
+ import lmdb
9
+ import pickle
10
+ import gc
11
+ import random
12
+ import multiprocessing as mp
13
+ from typing import Optional, List, Dict, Tuple
14
+ from torch.utils.data import Dataset, Subset
15
+ from tqdm import tqdm
16
+
17
+ def random_axis_rotation(data: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
18
+ """Random in-plane rotation augmentation."""
19
+ angle = random.uniform(0, 2 * np.pi)
20
+ cos_a, sin_a = np.cos(angle), np.sin(angle)
21
+ R = np.array([[cos_a, -sin_a, 0], [sin_a, cos_a, 0], [0, 0, 1]], dtype=np.float32)
22
+
23
+ keys_to_rotate = ['initial_mesh', 'drag_point', 'drag_vector', 'joint_axis',
24
+ 'joint_origin', 'rotation_direction', 'trajectory_vectors', 'drag_trajectory']
25
+ for k in keys_to_rotate:
26
+ if k in data:
27
+ val = data[k]
28
+ if isinstance(val, np.ndarray) and val.shape[-1] == 3:
29
+ data[k] = val @ R.T
30
+ return data
31
+
32
+ def get_motion_type_weights(dataset: Dataset, target_ratio: float = 3.0) -> torch.Tensor:
33
+ """Compute class-balancing weights for WeightedRandomSampler."""
34
+ indices = dataset.indices if isinstance(dataset, Subset) else range(len(dataset))
35
+ base_dataset = dataset.dataset if isinstance(dataset, Subset) else dataset
36
+
37
+ revolute_indices = []
38
+ prismatic_indices = []
39
+
40
+ print("Analyzing dataset motion types...")
41
+ for idx_in_subset, i in enumerate(tqdm(indices)):
42
+ try:
43
+ sample = base_dataset[i]
44
+ if sample is None: continue
45
+ jt = sample['joint_type'].item() if hasattr(sample['joint_type'], 'item') else sample['joint_type']
46
+ if jt == 0: revolute_indices.append(idx_in_subset)
47
+ elif jt == 1: prismatic_indices.append(idx_in_subset)
48
+ except: continue
49
+
50
+ weights = torch.ones(len(dataset), dtype=torch.double)
51
+ if not revolute_indices or not prismatic_indices:
52
+ return weights
53
+
54
+ n_rev, n_pri = len(revolute_indices), len(prismatic_indices)
55
+ if n_rev / n_pri > target_ratio:
56
+ w_rev, w_pri = (n_pri * target_ratio) / n_rev, 1.0
57
+ else:
58
+ w_rev, w_pri = 1.0, (n_rev / target_ratio) / n_pri
59
+
60
+ weights[revolute_indices] = w_rev
61
+ weights[prismatic_indices] = w_pri
62
+ return weights
63
+
64
+ # --- Worker helpers (used by optional multiprocessing / sequential fallback) ---
65
+ def _worker_init(ds):
66
+ global _global_dataset
67
+ _global_dataset = ds
68
+
69
+ def _worker_process_sample(idx):
70
+ """Worker-side sample serialization."""
71
+ try:
72
+ sample = _global_dataset[idx]
73
+ if sample is None:
74
+ return None
75
+
76
+ serialized = {}
77
+ keys_to_save = [
78
+ 'initial_mesh', 'drag_point', 'drag_vector', 'qr_gt', 'qd_gt',
79
+ 'joint_type', 'joint_axis', 'joint_origin', 'part_mask',
80
+ 'norm_center', 'norm_scale', 'origin_normalization_version',
81
+ 'rotation_direction', 'trajectory_vectors', 'drag_trajectory'
82
+ ]
83
+ for k in keys_to_save:
84
+ if k in sample:
85
+ val = sample[k]
86
+ if isinstance(val, torch.Tensor):
87
+ serialized[k] = val.numpy()
88
+ else:
89
+ serialized[k] = val
90
+ return serialized
91
+ except Exception:
92
+ return None
93
+
94
+ def build_vae_lmdb(dataset, output_path, categories=None, num_frames=16, num_points=4096):
95
+ """
96
+ Build an LMDB for VAE training.
97
+
98
+ Notes:
99
+ - In some environments (especially after torch/OMP initialization), multiprocessing with the
100
+ default fork start method may deadlock (symptoms: progress bar stuck; processes in futex_wait).
101
+ Since the loader already supports low-memory streaming point sampling, the default here is a
102
+ sequential build for stability.
103
+ - Fixes the "'int' object has no attribute 'size'" error when parsing joint_type.
104
+ """
105
+ print("\n" + "="*70)
106
+ print("BUILDING VAE LMDB DATABASE")
107
+ print("="*70)
108
+
109
+ total_samples = len(dataset)
110
+ # Open LMDB environment (100GB map size by default).
111
+ env = lmdb.open(output_path, map_size=1024**3 * 100)
112
+
113
+ actual_count = 0
114
+ revolute_count = 0
115
+ prismatic_count = 0
116
+
117
+ # Default: sequential execution to avoid mp/fork deadlocks.
118
+ global _global_dataset
119
+ _global_dataset = dataset
120
+ pbar = tqdm(range(total_samples), total=total_samples, desc="Writing LMDB")
121
+ for idx in pbar:
122
+ serialized = _worker_process_sample(idx)
123
+ if serialized is None:
124
+ continue
125
+
126
+ # --- Robust joint_type parsing ---
127
+ jt_val = serialized.get('joint_type')
128
+ if jt_val is not None:
129
+ # Handle numpy arrays
130
+ if isinstance(jt_val, np.ndarray):
131
+ jt = int(jt_val.item()) if jt_val.size == 1 else int(jt_val[0])
132
+ # Handle python scalars / sequences (int, float, list, ...)
133
+ else:
134
+ jt = int(jt_val[0]) if isinstance(jt_val, (list, tuple)) else int(jt_val)
135
+
136
+ if jt == 0: revolute_count += 1
137
+ else: prismatic_count += 1
138
+
139
+ # Write LMDB entry.
140
+ with env.begin(write=True) as txn:
141
+ key = f"{actual_count:08d}".encode('ascii')
142
+ txn.put(key, pickle.dumps(serialized))
143
+ actual_count += 1
144
+
145
+ del serialized
146
+ if actual_count % 100 == 0:
147
+ gc.collect()
148
+
149
+ # Write metadata.
150
+ with env.begin(write=True) as txn:
151
+ metadata = {
152
+ 'num_samples': actual_count, 'num_frames': num_frames, 'num_points': num_points,
153
+ 'categories': categories, 'revolute_count': revolute_count, 'prismatic_count': prismatic_count
154
+ }
155
+ txn.put(b'__metadata__', pickle.dumps(metadata))
156
+
157
+ env.close()
158
+ print(f"\nDone! Saved {actual_count} samples.")
159
+
160
+ class VAE_LMDBDataset(Dataset):
161
+ def __init__(self, lmdb_path: str, augment: bool = False):
162
+ self.env = lmdb.open(lmdb_path, readonly=True, lock=False, readahead=False, meminit=False)
163
+ self.augment = augment
164
+ with self.env.begin(write=False) as txn:
165
+ meta = txn.get(b'__metadata__')
166
+ if meta is None: raise ValueError("Corrupt LMDB!")
167
+ self.metadata = pickle.loads(meta)
168
+ self.num_samples = self.metadata['num_samples']
169
+
170
+ def __len__(self): return self.num_samples
171
+
172
+ def __getitem__(self, idx: int):
173
+ key = f"{idx:08d}".encode('ascii')
174
+ with self.env.begin(write=False) as txn:
175
+ data = txn.get(key)
176
+ if not data: return None
177
+
178
+ np_data = pickle.loads(data)
179
+
180
+ if self.augment and random.random() < 0.5:
181
+ np_data = random_axis_rotation(np_data)
182
+
183
+ res = {}
184
+ for k, v in np_data.items():
185
+ if isinstance(v, np.ndarray):
186
+ if v.dtype == np.float64: v = v.astype(np.float32)
187
+ res[k] = torch.from_numpy(v)
188
+ else:
189
+ res[k] = torch.tensor(v)
190
+
191
+ if 'joint_type' in res: res['joint_type'] = res['joint_type'].long()
192
+ res['is_cross_category'] = torch.tensor(0).long()
193
+ return res
DragMesh/dragmesh/data/data_loader_v2.py ADDED
@@ -0,0 +1,939 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import trimesh
4
+ import xml.etree.ElementTree as ET
5
+ from typing import Dict, List, Tuple, Optional
6
+ from collections import deque
7
+ import gc
8
+ import torch
9
+ import torch.nn.functional as F
10
+
11
+ from dragmesh.utils.kpp_normalization import mesh_center_scale, normalize_points, normalize_vector
12
+
13
+
14
+
15
+ def axis_angle_to_dualquat(axis: np.ndarray, origin: np.ndarray, angle: float) -> Tuple[np.ndarray, np.ndarray]:
16
+ """
17
+ Convert axis-angle representation to dual quaternion for revolute joint.
18
+ """
19
+ # Normalize axis
20
+ axis = axis / (np.linalg.norm(axis) + 1e-8)
21
+
22
+ # Rotation quaternion from axis-angle
23
+ half_angle = angle / 2.0
24
+ sin_half = np.sin(half_angle)
25
+ cos_half = np.cos(half_angle)
26
+
27
+ qr = np.array([cos_half, axis[0] * sin_half, axis[1] * sin_half, axis[2] * sin_half])
28
+
29
+ # Translation quaternion
30
+ t_vec = origin - quaternion_rotate(qr, origin)
31
+ t = np.array([0.0, t_vec[0], t_vec[1], t_vec[2]])
32
+
33
+ qd = 0.5 * quaternion_multiply(t, qr)
34
+
35
+ return qr, qd
36
+
37
+
38
+ def translation_to_dualquat(axis: np.ndarray, distance: float) -> Tuple[np.ndarray, np.ndarray]:
39
+ """
40
+ Convert translation to dual quaternion for prismatic joint.
41
+ """
42
+ # Normalize axis
43
+ axis = axis / (np.linalg.norm(axis) + 1e-8)
44
+
45
+ # No rotation for prismatic joint
46
+ qr = np.array([1.0, 0.0, 0.0, 0.0])
47
+
48
+ # Translation vector
49
+ t_vec = axis * distance
50
+ t = np.array([0.0, t_vec[0], t_vec[1], t_vec[2]])
51
+
52
+ # qd = 0.5 * quaternion_mul(t, qr) = 0.5 * t (since qr is identity)
53
+ qd = 0.5 * t
54
+
55
+ return qr, qd
56
+
57
+
58
+ def quaternion_multiply(q1: np.ndarray, q2: np.ndarray) -> np.ndarray:
59
+ """Multiply two quaternions."""
60
+ w1, x1, y1, z1 = q1
61
+ w2, x2, y2, z2 = q2
62
+
63
+ w = w1*w2 - x1*x2 - y1*y2 - z1*z2
64
+ x = w1*x2 + x1*w2 + y1*z2 - z1*y2
65
+ y = w1*y2 - x1*z2 + y1*w2 + z1*x2
66
+ z = w1*z2 + x1*y2 - y1*x2 + z1*w2
67
+
68
+ return np.array([w, x, y, z])
69
+
70
+
71
+ def quaternion_conjugate(q: np.ndarray) -> np.ndarray:
72
+ """Compute quaternion conjugate."""
73
+ return np.array([q[0], -q[1], -q[2], -q[3]])
74
+
75
+
76
+ def quaternion_rotate(q: np.ndarray, point: np.ndarray) -> np.ndarray:
77
+ """Apply quaternion rotation to a 3D point."""
78
+ p = np.array([0.0, point[0], point[1], point[2]])
79
+ q_conj = quaternion_conjugate(q)
80
+ rotated = quaternion_multiply(quaternion_multiply(q, p), q_conj)
81
+ return rotated[1:]
82
+
83
+
84
+
85
+ class GAPartNetLoaderV2:
86
+ """
87
+ Data loader for GAPartNet with Dual Quaternion ground truth.
88
+ """
89
+
90
+ def __init__(self, dataset_root: str):
91
+ self.dataset_root = dataset_root
92
+ self.object_list = self._get_object_list()
93
+
94
+ def _get_object_list(self) -> List[str]:
95
+ """Get list of all object directories in the dataset."""
96
+ object_list = []
97
+ # Support the case where dataset_root directly points to an object folder.
98
+ if os.path.exists(os.path.join(self.dataset_root, "mobility_annotation_gapartnet.urdf")):
99
+ return [self.dataset_root]
100
+
101
+ for category in os.listdir(self.dataset_root):
102
+ category_path = os.path.join(self.dataset_root, category)
103
+ if not os.path.isdir(category_path):
104
+ continue
105
+
106
+ # Support the case where the category directory itself contains the URDF.
107
+ if os.path.exists(os.path.join(category_path, "mobility_annotation_gapartnet.urdf")):
108
+ object_list.append(category_path)
109
+ continue
110
+
111
+ for obj_id in os.listdir(category_path):
112
+ obj_path = os.path.join(category_path, obj_id)
113
+ urdf_path = os.path.join(obj_path, "mobility_annotation_gapartnet.urdf")
114
+ if os.path.exists(urdf_path):
115
+ object_list.append(obj_path)
116
+ return object_list
117
+
118
+ def parse_urdf(self, urdf_path: str) -> Dict:
119
+ """Parse URDF file to extract joint information."""
120
+ tree = ET.parse(urdf_path)
121
+ root = tree.getroot()
122
+
123
+ joints = []
124
+ links = {}
125
+
126
+ # Parse links and extract ALL mesh filenames
127
+ for link in root.findall('link'):
128
+ link_name = link.get('name')
129
+ # Keep the link entry even if it has no mesh: it can still be a joint attachment.
130
+ mesh_files = []
131
+ for visual in link.findall('visual'):
132
+ geometry = visual.find('geometry')
133
+ if geometry is not None:
134
+ mesh = geometry.find('mesh')
135
+ if mesh is not None:
136
+ mesh_filename = mesh.get('filename')
137
+ if mesh_filename not in mesh_files: # Avoid duplicates
138
+ mesh_files.append(mesh_filename)
139
+ links[link_name] = mesh_files
140
+
141
+ # Parse joints (only movable joints are added to the `joints` list).
142
+ for joint in root.findall('joint'):
143
+ joint_type = joint.get('type')
144
+ if joint_type == 'fixed':
145
+ continue
146
+
147
+ joint_name = joint.get('name')
148
+ parent = joint.find('parent').get('link')
149
+ child = joint.find('child').get('link')
150
+
151
+ axis_elem = joint.find('axis')
152
+ if axis_elem is not None:
153
+ axis = [float(x) for x in axis_elem.get('xyz').split()]
154
+ else:
155
+ axis = [0, 0, 1]
156
+
157
+ origin_elem = joint.find('origin')
158
+ if origin_elem is not None:
159
+ xyz_str = origin_elem.get('xyz')
160
+ rpy_str = origin_elem.get('rpy')
161
+ xyz = [float(x) for x in xyz_str.split()] if xyz_str else [0, 0, 0]
162
+ rpy = [float(x) for x in rpy_str.split()] if rpy_str else [0, 0, 0]
163
+ else:
164
+ xyz = [0, 0, 0]
165
+ rpy = [0, 0, 0]
166
+
167
+ limit_elem = joint.find('limit')
168
+ if limit_elem is not None:
169
+ lower = float(limit_elem.get('lower'))
170
+ upper = float(limit_elem.get('upper'))
171
+ else:
172
+ lower = -1.57
173
+ upper = 1.57
174
+
175
+ joints.append({
176
+ 'name': joint_name,
177
+ 'type': joint_type,
178
+ 'parent': parent,
179
+ 'child': child,
180
+ 'axis': np.array(axis),
181
+ 'origin_xyz': np.array(xyz),
182
+ 'origin_rpy': np.array(rpy),
183
+ 'limit': {'lower': lower, 'upper': upper}
184
+ })
185
+
186
+ # --- Build a full tree map (including fixed joints) ---
187
+ # This is important for propagating motion to descendant links (e.g., handle follows door).
188
+ full_tree_map = {}
189
+ for joint in root.findall('joint'):
190
+ p = joint.find('parent').get('link')
191
+ c = joint.find('child').get('link')
192
+ if p not in full_tree_map:
193
+ full_tree_map[p] = []
194
+ full_tree_map[p].append(c)
195
+
196
+ return {'joints': joints, 'links': links, 'full_tree_map': full_tree_map}
197
+
198
+ def _get_subtree_links(self, root_link: str, tree_map: Dict[str, List[str]]) -> List[str]:
199
+ """
200
+ Collect all descendant links starting from `root_link` (including itself).
201
+ """
202
+ subtree: List[str] = []
203
+ seen = set()
204
+ queue = deque([root_link])
205
+ while queue:
206
+ current = queue.popleft()
207
+ if current in seen:
208
+ continue
209
+ seen.add(current)
210
+ subtree.append(current)
211
+ for child in tree_map.get(current, []):
212
+ queue.append(child)
213
+ return subtree
214
+
215
+ def _joint_motion_span(self, joint: Dict) -> float:
216
+ """Estimate motion span to pick a representative joint (avoid tiny first-part joints)."""
217
+ jtype = joint.get('type')
218
+ if jtype == 'continuous':
219
+ return float(2.0 * np.pi)
220
+ lower = float(joint.get('limit', {}).get('lower', -1.57))
221
+ upper = float(joint.get('limit', {}).get('upper', 1.57))
222
+ span = abs(upper - lower)
223
+ # Some joints have near-zero ranges (e.g., buttons with 0.005). Avoid degeneracy.
224
+ if not np.isfinite(span) or span < 1e-6:
225
+ return float(np.pi / 6.0) if jtype in ['revolute'] else 0.01
226
+ return float(span)
227
+
228
+ def _select_joint_and_moving_links(
229
+ self,
230
+ urdf_data: Dict,
231
+ part_meshes: Optional[Dict[str, trimesh.Trimesh]] = None,
232
+ links: Optional[Dict[str, List[str]]] = None,
233
+ obj_path: Optional[str] = None,
234
+ joint_selection: str = "largest_motion",
235
+ joint_idx: Optional[int] = None,
236
+ ) -> Tuple[Dict, List[str]]:
237
+ """
238
+ Select a joint for sample generation and return the corresponding moving-subtree links.
239
+
240
+ - joint_selection:
241
+ - "first": the first movable joint
242
+ - "random": a random movable joint
243
+ - "largest_motion": maximize (motion span) × (moving geometry scale). Recommended default to
244
+ avoid selecting tiny parts such as small buttons.
245
+ """
246
+ joints: List[Dict] = urdf_data.get('joints', [])
247
+ if not joints:
248
+ raise ValueError("No movable joints found")
249
+
250
+ if joint_idx is not None:
251
+ if joint_idx < 0 or joint_idx >= len(joints):
252
+ raise IndexError(f"joint_idx {joint_idx} out of range (0..{len(joints)-1})")
253
+ joint = joints[joint_idx]
254
+ moving_links = self._get_subtree_links(joint['child'], urdf_data['full_tree_map'])
255
+ return joint, moving_links
256
+
257
+ if joint_selection == "first":
258
+ joint = joints[0]
259
+ moving_links = self._get_subtree_links(joint['child'], urdf_data['full_tree_map'])
260
+ return joint, moving_links
261
+
262
+ if joint_selection == "random":
263
+ joint = joints[int(np.random.randint(0, len(joints)))]
264
+ moving_links = self._get_subtree_links(joint['child'], urdf_data['full_tree_map'])
265
+ return joint, moving_links
266
+
267
+ # Default: "largest_motion"
268
+ best_joint = None
269
+ best_links: List[str] = []
270
+ best_score = -1.0
271
+ for j in joints:
272
+ subtree_links = self._get_subtree_links(j['child'], urdf_data['full_tree_map'])
273
+ # Estimate moving geometry scale (prefer vertex count; otherwise use mesh-file count as a proxy).
274
+ geom_score = 0
275
+ if part_meshes is not None:
276
+ for ln in subtree_links:
277
+ mesh = part_meshes.get(ln)
278
+ if mesh is not None:
279
+ geom_score += int(len(mesh.vertices))
280
+ else:
281
+ links_dict = links
282
+ if links_dict is None or obj_path is None:
283
+ geom_score = 0
284
+ else:
285
+ for ln in subtree_links:
286
+ for fn in (links_dict.get(ln) or []):
287
+ if os.path.exists(os.path.join(obj_path, fn)):
288
+ geom_score += 1
289
+
290
+ if geom_score <= 0:
291
+ continue
292
+
293
+ score = float(geom_score) * self._joint_motion_span(j)
294
+ if score > best_score:
295
+ best_score = score
296
+ best_joint = j
297
+ best_links = subtree_links
298
+
299
+ if best_joint is None:
300
+ # Fallback to "first".
301
+ joint = joints[0]
302
+ moving_links = self._get_subtree_links(joint['child'], urdf_data['full_tree_map'])
303
+ return joint, moving_links
304
+
305
+ return best_joint, best_links
306
+
307
+ def load_part_meshes(self, obj_path: str, links: Dict[str, List[str]]) -> Dict[str, trimesh.Trimesh]:
308
+ """
309
+ Load meshes for each part/link.
310
+ """
311
+ part_meshes = {}
312
+
313
+ for link_name, mesh_filenames in links.items():
314
+ link_meshes = []
315
+ for mesh_filename in mesh_filenames:
316
+ mesh_path = os.path.join(obj_path, mesh_filename)
317
+ if os.path.exists(mesh_path):
318
+ try:
319
+ mesh = trimesh.load(mesh_path, force='mesh', process=False)
320
+ link_meshes.append(mesh)
321
+ except Exception as e:
322
+ # print(f"Warning: Failed to load {mesh_path}: {e}")
323
+ pass
324
+
325
+ if len(link_meshes) > 0:
326
+ if len(link_meshes) == 1:
327
+ part_meshes[link_name] = link_meshes[0]
328
+ else:
329
+ combined_mesh = trimesh.util.concatenate(link_meshes)
330
+ part_meshes[link_name] = combined_mesh
331
+
332
+ return part_meshes
333
+
334
+ def _load_mesh_safe(self, mesh_path: str) -> Optional[trimesh.Trimesh]:
335
+ """
336
+ More robust mesh loading:
337
+ - Accept trimesh.Scene outputs
338
+ - Keep process=False to avoid unnecessary recomputation
339
+ """
340
+ if not os.path.exists(mesh_path):
341
+ return None
342
+ try:
343
+ m = trimesh.load(mesh_path, force='mesh', process=False)
344
+ except Exception:
345
+ return None
346
+
347
+ if isinstance(m, trimesh.Scene):
348
+ geoms = [g for g in m.geometry.values() if isinstance(g, trimesh.Trimesh)]
349
+ if not geoms:
350
+ return None
351
+ try:
352
+ m = trimesh.util.concatenate(geoms)
353
+ except Exception:
354
+ return None
355
+
356
+ if not isinstance(m, trimesh.Trimesh):
357
+ return None
358
+ if m.vertices is None or m.faces is None:
359
+ return None
360
+ if len(m.vertices) == 0 or len(m.faces) == 0:
361
+ return None
362
+ return m
363
+
364
+ def _stream_sample_points(
365
+ self,
366
+ obj_path: str,
367
+ links: Dict[str, List[str]],
368
+ moving_links: set,
369
+ num_points: int,
370
+ joint_origin: np.ndarray,
371
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
372
+ """
373
+ Low-memory mode: avoid mesh concatenation.
374
+ Load each mesh file -> sample points -> release immediately.
375
+
376
+ Returns:
377
+ - points: [num_points, 3] float32
378
+ - point_mask: [num_points] int32 (0=static, 1=movable)
379
+ - movable_points: [K, 3] float32 (only for drag-point sampling; K<=num_points)
380
+ - bounds_min: [3] float32
381
+ - bounds_max: [3] float32
382
+ """
383
+ # Count available mesh files to allocate per-mesh sampling budget.
384
+ mesh_entries: List[Tuple[str, int]] = [] # (mesh_path, is_moving)
385
+ for link_name, mesh_filenames in links.items():
386
+ is_moving = 1 if link_name in moving_links else 0
387
+ for mesh_filename in mesh_filenames:
388
+ mesh_path = os.path.join(obj_path, mesh_filename)
389
+ if os.path.exists(mesh_path):
390
+ mesh_entries.append((mesh_path, is_moving))
391
+
392
+ if not mesh_entries:
393
+ raise ValueError(f"No meshes found under {obj_path}")
394
+
395
+ n_total = len(mesh_entries)
396
+ base = max(1, int(num_points // n_total))
397
+ rem = int(num_points - base * n_total)
398
+ if rem < 0:
399
+ rem = 0
400
+
401
+ all_points = []
402
+ all_masks = []
403
+ movable_points = []
404
+
405
+ bounds_min = np.array([np.inf, np.inf, np.inf], dtype=np.float32)
406
+ bounds_max = np.array([-np.inf, -np.inf, -np.inf], dtype=np.float32)
407
+
408
+ # Sample points per mesh.
409
+ for i, (mesh_path, is_moving) in enumerate(mesh_entries):
410
+ n_i = base + (1 if i < rem else 0)
411
+ if n_i <= 0:
412
+ continue
413
+
414
+ mesh = self._load_mesh_safe(mesh_path)
415
+ if mesh is None:
416
+ continue
417
+
418
+ # Accumulate bounds.
419
+ try:
420
+ b = mesh.bounds.astype(np.float32)
421
+ bounds_min = np.minimum(bounds_min, b[0])
422
+ bounds_max = np.maximum(bounds_max, b[1])
423
+ except Exception:
424
+ pass
425
+
426
+ try:
427
+ pts, _ = trimesh.sample.sample_surface(mesh, n_i)
428
+ except Exception:
429
+ del mesh
430
+ continue
431
+
432
+ pts = pts.astype(np.float32, copy=False)
433
+ mask = np.full((len(pts),), int(is_moving), dtype=np.int32)
434
+
435
+ all_points.append(pts)
436
+ all_masks.append(mask)
437
+ if is_moving:
438
+ movable_points.append(pts)
439
+
440
+ # Proactively release large objects to reduce peak memory.
441
+ del mesh
442
+ if (i % 10) == 0:
443
+ gc.collect()
444
+
445
+ if not all_points:
446
+ raise ValueError(f"Failed to sample any points from {obj_path}")
447
+
448
+ points = np.concatenate(all_points, axis=0)
449
+ point_mask = np.concatenate(all_masks, axis=0)
450
+
451
+ # Trim/pad to exactly num_points (meshes may fail to load, causing mismatch).
452
+ if len(points) >= num_points:
453
+ points = points[:num_points]
454
+ point_mask = point_mask[:num_points]
455
+ else:
456
+ # If insufficient, pad by resampling with replacement (avoid downstream failures).
457
+ pad_n = num_points - len(points)
458
+ rep_idx = np.random.randint(0, len(points), size=pad_n)
459
+ points = np.concatenate([points, points[rep_idx]], axis=0)
460
+ point_mask = np.concatenate([point_mask, point_mask[rep_idx]], axis=0)
461
+
462
+ if movable_points:
463
+ movable_points = np.concatenate(movable_points, axis=0)
464
+ else:
465
+ movable_points = points[point_mask.astype(bool)]
466
+
467
+ if movable_points is None or len(movable_points) == 0:
468
+ raise ValueError("No movable points sampled (moving subtree has no geometry?)")
469
+
470
+ # If bounds were not updated (extreme edge cases), fall back to point-cloud bounds.
471
+ if not np.isfinite(bounds_min).all() or not np.isfinite(bounds_max).all():
472
+ bounds_min = points.min(axis=0).astype(np.float32)
473
+ bounds_max = points.max(axis=0).astype(np.float32)
474
+
475
+ return points, point_mask, movable_points, bounds_min, bounds_max
476
+
477
+ def generate_training_sample(
478
+ self,
479
+ obj_idx: int,
480
+ num_frames: int = 16,
481
+ joint_selection: str = "largest_motion",
482
+ joint_idx: Optional[int] = None,
483
+ return_mesh: bool = True,
484
+ num_points: Optional[int] = None,
485
+ ) -> Dict:
486
+ """
487
+ Generate training sample with dual quaternion ground truth.
488
+ Fix motion leakage by recursively collecting all descendant moving parts.
489
+ """
490
+ obj_path = self.object_list[obj_idx]
491
+
492
+ # Parse URDF
493
+ urdf_path = os.path.join(obj_path, "mobility_annotation_gapartnet.urdf")
494
+ urdf_data = self.parse_urdf(urdf_path)
495
+
496
+ if len(urdf_data['joints']) == 0:
497
+ raise ValueError(f"No movable joints found in {obj_path}")
498
+
499
+ # Select a joint for sample generation (default avoids always picking a tiny first joint).
500
+ # When return_mesh=False, avoid loading full meshes (OOM); use mesh-file count as a proxy score.
501
+ part_meshes = None
502
+ if return_mesh:
503
+ part_meshes = self.load_part_meshes(obj_path, urdf_data['links'])
504
+
505
+ joint, moving_links_list = self._select_joint_and_moving_links(
506
+ urdf_data=urdf_data,
507
+ part_meshes=part_meshes,
508
+ links=urdf_data.get('links'),
509
+ obj_path=obj_path,
510
+ joint_selection=joint_selection,
511
+ joint_idx=joint_idx,
512
+ )
513
+
514
+ # --- Core: descendant propagation ---
515
+ moving_root_link = joint['child']
516
+
517
+ # Use the full tree map to collect all links that should move with this joint
518
+ # (e.g., door -> handle, lock). `moving_root_link` may have many descendants via fixed joints.
519
+ all_moving_links = set(moving_links_list if moving_links_list else self._get_subtree_links(moving_root_link, urdf_data['full_tree_map']))
520
+
521
+ # ========== Low-memory point-cloud mode (for LMDB building) ==========
522
+ if not return_mesh:
523
+ if num_points is None:
524
+ raise ValueError("return_mesh=False requires num_points")
525
+
526
+ points, point_mask, movable_points, bounds_min, bounds_max = self._stream_sample_points(
527
+ obj_path=obj_path,
528
+ links=urdf_data['links'],
529
+ moving_links=all_moving_links,
530
+ num_points=int(num_points),
531
+ joint_origin=joint['origin_xyz'],
532
+ )
533
+
534
+ # Sample a drag point: pick a movable point far from the joint origin.
535
+ if joint['type'] in ['revolute', 'continuous']:
536
+ d = np.linalg.norm(movable_points - joint['origin_xyz'][None, :], axis=1)
537
+ if len(d) == 0:
538
+ raise ValueError("No movable points for drag sampling")
539
+ k = max(1, len(d) // 5) # top 20%
540
+ far_idx = np.argpartition(d, -k)[-k:]
541
+ drag_point_start = movable_points[np.random.choice(far_idx)].copy()
542
+
543
+ lower, upper = joint['limit']['lower'], joint['limit']['upper']
544
+ if upper - lower < np.pi:
545
+ lower, upper = -np.pi, np.pi
546
+ angle_change = upper - lower
547
+ rotation_direction = np.array(joint['axis']) * np.sign(angle_change)
548
+ else:
549
+ drag_point_start = movable_points[np.random.randint(0, len(movable_points))].copy()
550
+ rotation_direction = None
551
+
552
+ # Subsequent steps (DQ sequence / trajectory generation) follow the original logic.
553
+ lower, upper = joint['limit']['lower'], joint['limit']['upper']
554
+
555
+ if joint['type'] == 'continuous':
556
+ upper = max(upper, np.pi)
557
+ lower = min(lower, -np.pi)
558
+
559
+ if upper <= lower:
560
+ upper = lower + 1.0
561
+
562
+ if upper > lower:
563
+ angles = np.linspace(lower, upper, num_frames)
564
+ else:
565
+ if joint['type'] == 'continuous':
566
+ angles = np.linspace(-np.pi, np.pi, num_frames)
567
+ else:
568
+ angles = np.linspace(0, np.pi/2, num_frames)
569
+
570
+ qr_sequence = []
571
+ qd_sequence = []
572
+ for angle in angles:
573
+ if joint['type'] == 'revolute' or joint['type'] == 'continuous':
574
+ qr, qd = axis_angle_to_dualquat(joint['axis'], joint['origin_xyz'], angle)
575
+ elif joint['type'] == 'prismatic':
576
+ qr, qd = translation_to_dualquat(joint['axis'], angle)
577
+ else:
578
+ raise ValueError(f"Unknown joint type: {joint['type']}")
579
+ qr_sequence.append(qr)
580
+ qd_sequence.append(qd)
581
+
582
+ qr_sequence = np.array(qr_sequence)
583
+ qd_sequence = np.array(qd_sequence)
584
+
585
+ drag_trajectory = []
586
+ for qr, qd in zip(qr_sequence, qd_sequence):
587
+ point_rotated = quaternion_rotate(qr, drag_point_start)
588
+ t_vec = 2.0 * quaternion_multiply(qd, quaternion_conjugate(qr))[1:]
589
+ drag_trajectory.append(point_rotated + t_vec)
590
+ drag_trajectory = np.array(drag_trajectory)
591
+
592
+ if len(drag_trajectory) > 2:
593
+ start_tangent = drag_trajectory[1] - drag_trajectory[0]
594
+ mid_idx = len(drag_trajectory) // 2
595
+ mid_tangent = drag_trajectory[mid_idx+1] - drag_trajectory[mid_idx]
596
+ end_tangent = drag_trajectory[-1] - drag_trajectory[-2]
597
+ trajectory_vectors = np.stack([start_tangent, mid_tangent, end_tangent])
598
+ else:
599
+ diff = drag_trajectory[-1] - drag_trajectory[0]
600
+ trajectory_vectors = np.stack([diff, diff, diff])
601
+
602
+ diffs = drag_trajectory[1:] - drag_trajectory[:-1]
603
+ lengths = np.linalg.norm(diffs, axis=1)
604
+ total_length = lengths.sum()
605
+ if total_length > 0:
606
+ avg_dir = np.mean(trajectory_vectors, axis=0)
607
+ avg_dir = avg_dir / (np.linalg.norm(avg_dir) + 1e-8)
608
+ drag_vector = avg_dir * total_length
609
+ else:
610
+ drag_vector = drag_trajectory[-1] - drag_trajectory[0]
611
+
612
+ rotation_direction = None
613
+ if joint['type'] in ['revolute', 'continuous']:
614
+ if len(angles) >= 2:
615
+ angle_change = angles[-1] - angles[0]
616
+ rotation_direction = np.array(joint['axis']) * np.sign(angle_change)
617
+ else:
618
+ rotation_direction = np.array(joint['axis'])
619
+
620
+ drag_dir = drag_vector / (np.linalg.norm(drag_vector) + 1e-8)
621
+ relative_point = drag_point_start - joint['origin_xyz']
622
+ cross_axis_drag = np.cross(joint['axis'], drag_dir)
623
+ rotation_sign = np.sign(np.dot(cross_axis_drag, relative_point)) or 1.0
624
+
625
+ if rotation_direction is None:
626
+ rotation_direction = np.array(joint['axis'])
627
+
628
+ rotation_direction = rotation_direction * rotation_sign
629
+ drag_vector = drag_vector * rotation_sign
630
+
631
+ return {
632
+ # Use ndarray instead of trimesh so upstream datasets can normalize/write LMDB directly.
633
+ 'initial_mesh': points.astype(np.float32, copy=False),
634
+ 'drag_point': drag_point_start.astype(np.float32, copy=False),
635
+ 'drag_vector': drag_vector.astype(np.float32, copy=False),
636
+ 'trajectory_vectors': trajectory_vectors.astype(np.float32, copy=False),
637
+ 'rotation_direction': rotation_direction.astype(np.float32, copy=False),
638
+ 'qr_sequence': qr_sequence.astype(np.float32, copy=False),
639
+ 'qd_sequence': qd_sequence.astype(np.float32, copy=False),
640
+ 'drag_trajectory': drag_trajectory.astype(np.float32, copy=False),
641
+ 'joint_type': joint['type'],
642
+ # point-level mask (0=static, 1=movable)
643
+ 'part_mask': point_mask.astype(np.int32, copy=False),
644
+ 'obj_path': obj_path,
645
+ 'joint_axis': joint['axis'],
646
+ 'joint_origin': joint['origin_xyz'],
647
+ # Optionally return bounds for upstream normalization.
648
+ 'bounds_min': bounds_min,
649
+ 'bounds_max': bounds_max,
650
+ }
651
+
652
+ # ========== Full mesh concatenation mode (for inference / visualization) ==========
653
+ if part_meshes is None:
654
+ part_meshes = self.load_part_meshes(obj_path, urdf_data['links'])
655
+ # Gather moving meshes and static meshes.
656
+ movable_meshes_list = []
657
+ static_meshes_list = []
658
+
659
+ for link_name, mesh in part_meshes.items():
660
+ if link_name in all_moving_links:
661
+ movable_meshes_list.append(mesh)
662
+ else:
663
+ static_meshes_list.append(mesh)
664
+
665
+ if not movable_meshes_list:
666
+ raise ValueError(f"Child link {moving_root_link} (and descendants) have no meshes")
667
+
668
+ # Concatenate all moving parts.
669
+ child_mesh = trimesh.util.concatenate(movable_meshes_list)
670
+
671
+ # Sample a drag point.
672
+ if joint['type'] in ['revolute', 'continuous']:
673
+ # Sample the farthest point over the whole moving part.
674
+ distances = np.linalg.norm(child_mesh.vertices - joint['origin_xyz'], axis=1)
675
+ far_indices = np.argsort(distances)[-max(1, len(child_mesh.vertices) // 5):] # Top 20%
676
+ drag_point_idx = np.random.choice(far_indices)
677
+ drag_point_start = child_mesh.vertices[drag_point_idx].copy()
678
+
679
+ # Improve angle range
680
+ lower, upper = joint['limit']['lower'], joint['limit']['upper']
681
+ if upper - lower < np.pi:
682
+ lower, upper = -np.pi, np.pi
683
+
684
+ # For rotation_direction
685
+ angle_change = upper - lower
686
+ rotation_direction = np.array(joint['axis']) * np.sign(angle_change)
687
+
688
+ else:
689
+ drag_point_idx = np.random.randint(0, len(child_mesh.vertices))
690
+ drag_point_start = child_mesh.vertices[drag_point_idx].copy()
691
+
692
+ # Generate dual quaternion sequence
693
+ lower, upper = joint['limit']['lower'], joint['limit']['upper']
694
+
695
+ if joint['type'] == 'continuous':
696
+ upper = max(upper, np.pi)
697
+ lower = min(lower, -np.pi)
698
+
699
+ # Protect against weird limits
700
+ if upper <= lower:
701
+ upper = lower + 1.0
702
+
703
+ if upper > lower:
704
+ angles = np.linspace(lower, upper, num_frames)
705
+ else:
706
+ if joint['type'] == 'continuous':
707
+ angles = np.linspace(-np.pi, np.pi, num_frames)
708
+ else:
709
+ angles = np.linspace(0, np.pi/2, num_frames)
710
+
711
+ qr_sequence = []
712
+ qd_sequence = []
713
+
714
+ for angle in angles:
715
+ if joint['type'] == 'revolute' or joint['type'] == 'continuous':
716
+ qr, qd = axis_angle_to_dualquat(
717
+ joint['axis'],
718
+ joint['origin_xyz'],
719
+ angle
720
+ )
721
+ elif joint['type'] == 'prismatic':
722
+ qr, qd = translation_to_dualquat(joint['axis'], angle)
723
+ else:
724
+ raise ValueError(f"Unknown joint type: {joint['type']}")
725
+
726
+ qr_sequence.append(qr)
727
+ qd_sequence.append(qd)
728
+
729
+ qr_sequence = np.array(qr_sequence) # [num_frames, 4]
730
+ qd_sequence = np.array(qd_sequence) # [num_frames, 4]
731
+
732
+ # Combine all parts into initial mesh (Static + Combined Movable)
733
+ if static_meshes_list:
734
+ static_mesh_combined = trimesh.util.concatenate(static_meshes_list)
735
+ initial_mesh = trimesh.util.concatenate([static_mesh_combined, child_mesh])
736
+
737
+ # Create part mask (0=static, 1=movable)
738
+ num_static_verts = len(static_mesh_combined.vertices)
739
+ num_movable_verts = len(child_mesh.vertices)
740
+ part_mask = np.concatenate([
741
+ np.zeros(num_static_verts, dtype=np.int32),
742
+ np.ones(num_movable_verts, dtype=np.int32)
743
+ ])
744
+ else:
745
+ # Only the moving part is present.
746
+ initial_mesh = child_mesh
747
+ part_mask = np.ones(len(child_mesh.vertices), dtype=np.int32)
748
+
749
+ # Calculate drag vector with trajectory information
750
+ drag_trajectory = []
751
+ for qr, qd in zip(qr_sequence, qd_sequence):
752
+ point_rotated = quaternion_rotate(qr, drag_point_start)
753
+ t_vec = 2.0 * quaternion_multiply(qd, quaternion_conjugate(qr))[1:]
754
+ point_transformed = point_rotated + t_vec
755
+ drag_trajectory.append(point_transformed)
756
+
757
+ drag_trajectory = np.array(drag_trajectory) # [num_frames, 3]
758
+
759
+ # Multi-tangent
760
+ if len(drag_trajectory) > 2:
761
+ start_tangent = drag_trajectory[1] - drag_trajectory[0]
762
+ mid_idx = len(drag_trajectory) // 2
763
+ mid_tangent = drag_trajectory[mid_idx+1] - drag_trajectory[mid_idx]
764
+ end_tangent = drag_trajectory[-1] - drag_trajectory[-2]
765
+ trajectory_vectors = np.stack([start_tangent, mid_tangent, end_tangent])
766
+ else:
767
+ # Fallback for very short trajectories
768
+ diff = drag_trajectory[-1] - drag_trajectory[0]
769
+ trajectory_vectors = np.stack([diff, diff, diff]) # Simple broadcast
770
+
771
+ # Improved drag_vector
772
+ diffs = drag_trajectory[1:] - drag_trajectory[:-1]
773
+ lengths = np.linalg.norm(diffs, axis=1)
774
+ total_length = lengths.sum()
775
+ if total_length > 0:
776
+ avg_dir = np.mean(trajectory_vectors, axis=0)
777
+ avg_dir = avg_dir / (np.linalg.norm(avg_dir) + 1e-8)
778
+ drag_vector = avg_dir * total_length
779
+ else:
780
+ drag_vector = drag_trajectory[-1] - drag_trajectory[0]
781
+
782
+ # Rotation Direction & Sign Fix
783
+ rotation_direction = None
784
+ if joint['type'] in ['revolute', 'continuous']:
785
+ if len(angles) >= 2:
786
+ angle_change = angles[-1] - angles[0]
787
+ rotation_direction = np.array(joint['axis']) * np.sign(angle_change)
788
+ else:
789
+ rotation_direction = np.array(joint['axis'])
790
+
791
+ drag_dir = drag_vector / (np.linalg.norm(drag_vector) + 1e-8)
792
+ relative_point = drag_point_start - joint['origin_xyz']
793
+ cross_axis_drag = np.cross(joint['axis'], drag_dir)
794
+ rotation_sign = np.sign(np.dot(cross_axis_drag, relative_point)) or 1.0
795
+
796
+ if rotation_direction is None:
797
+ rotation_direction = np.array(joint['axis'])
798
+
799
+ rotation_direction = rotation_direction * rotation_sign
800
+ drag_vector = drag_vector * rotation_sign
801
+
802
+ return {
803
+ 'initial_mesh': initial_mesh,
804
+ 'drag_point': drag_point_start,
805
+ 'drag_vector': drag_vector,
806
+ 'trajectory_vectors': trajectory_vectors,
807
+ 'rotation_direction': rotation_direction,
808
+ 'qr_sequence': qr_sequence,
809
+ 'qd_sequence': qd_sequence,
810
+ 'drag_trajectory': drag_trajectory, # extra field for LMDB checks
811
+ 'joint_type': joint['type'],
812
+ 'part_mask': part_mask,
813
+ 'obj_path': obj_path,
814
+ 'joint_axis': joint['axis'],
815
+ 'joint_origin': joint['origin_xyz']
816
+ }
817
+
818
+ def __len__(self):
819
+ return len(self.object_list)
820
+
821
+
822
+ # ==============================================================================
823
+ # DragMeshDatasetV2 (PyTorch Dataset)
824
+ # ==============================================================================
825
+
826
+ class DragMeshDatasetV2(torch.utils.data.Dataset):
827
+ """
828
+ PyTorch Dataset with Dual Quaternion ground truth.
829
+ """
830
+
831
+ def __init__(self, dataset_root: str, num_frames: int = 16, num_points: int = 4096, joint_selection: str = "largest_motion"):
832
+ self.loader = GAPartNetLoaderV2(dataset_root)
833
+ self.num_frames = num_frames
834
+ self.num_points = num_points
835
+ self.joint_selection = joint_selection
836
+
837
+ def mesh_to_pointcloud(self, mesh: trimesh.Trimesh, num_points: int) -> np.ndarray:
838
+ """Sample point cloud from mesh surface."""
839
+ points, face_idx = trimesh.sample.sample_surface(mesh, num_points)
840
+ return points
841
+
842
+ def normalize_mesh(self, mesh: trimesh.Trimesh) -> Tuple[trimesh.Trimesh, np.ndarray, float]:
843
+ """
844
+ Normalize mesh to unit bounding box centered at origin.
845
+ """
846
+ bounds = mesh.bounds
847
+ center = (bounds[0] + bounds[1]) / 2
848
+ scale = (bounds[1] - bounds[0]).max()
849
+
850
+ if scale < 1e-6:
851
+ scale = 1.0
852
+
853
+ mesh_normalized = mesh.copy()
854
+ mesh_normalized.vertices = (mesh_normalized.vertices - center) / scale
855
+ return mesh_normalized, center, scale
856
+
857
+ def __len__(self):
858
+ return len(self.loader)
859
+
860
+ def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
861
+ """
862
+ Get a training sample.
863
+ """
864
+ sample = self.loader.generate_training_sample(idx, self.num_frames, joint_selection=self.joint_selection)
865
+
866
+ # Use an inference-reproducible frame for KPP origin labels. The
867
+ # previous joint-origin-centered frame made the origin target always 0.
868
+ center, scale = mesh_center_scale(sample['initial_mesh'])
869
+
870
+ mesh_normalized_verts = normalize_points(sample['initial_mesh'].vertices, center, scale)
871
+ mesh_normalized = trimesh.Trimesh(vertices=mesh_normalized_verts,
872
+ faces=sample['initial_mesh'].faces)
873
+
874
+ initial_pc, face_idx = trimesh.sample.sample_surface(mesh_normalized, self.num_points)
875
+
876
+ drag_point = normalize_points(sample['drag_point'], center, scale)
877
+ drag_vector = normalize_vector(sample['drag_vector'], scale)
878
+
879
+ rotation_direction = sample.get('rotation_direction')
880
+ if rotation_direction is not None:
881
+ rotation_direction = np.array(rotation_direction)
882
+
883
+ trajectory_vectors = sample.get('trajectory_vectors')
884
+ if trajectory_vectors is not None:
885
+ trajectory_vectors = np.array(trajectory_vectors)
886
+
887
+ joint_origin_normalized = normalize_points(sample['joint_origin'], center, scale)
888
+
889
+ if sample['joint_type'] == 'revolute' or sample['joint_type'] == 'continuous':
890
+ joint_type = 0
891
+ elif sample['joint_type'] == 'prismatic':
892
+ joint_type = 1
893
+ else:
894
+ joint_type = 0 # default to revolute
895
+
896
+ qr_gt = sample['qr_sequence']
897
+
898
+ qd_gt = sample['qd_sequence'].copy()
899
+ qd_gt = qd_gt / scale
900
+
901
+ joint_axis = sample['joint_axis']
902
+ joint_axis = joint_axis / (np.linalg.norm(joint_axis) + 1e-8)
903
+
904
+ original_mesh = sample['initial_mesh']
905
+ vertex_part_mask = sample['part_mask'] # [N_verts]
906
+
907
+ sampled_part_mask = np.zeros(self.num_points, dtype=np.int32)
908
+ for i, fid in enumerate(face_idx):
909
+ face_vertices = original_mesh.faces[fid]
910
+ face_mask_values = vertex_part_mask[face_vertices]
911
+ sampled_part_mask[i] = np.bincount(face_mask_values.astype(int)).argmax()
912
+
913
+ result = {
914
+ 'initial_mesh': torch.from_numpy(initial_pc).float(),
915
+ 'drag_point': torch.from_numpy(drag_point).float(),
916
+ 'drag_vector': torch.from_numpy(drag_vector).float(),
917
+ 'qr_gt': torch.from_numpy(qr_gt).float(),
918
+ 'qd_gt': torch.from_numpy(qd_gt).float(),
919
+ 'joint_type': torch.tensor(joint_type).long(),
920
+ 'joint_axis': torch.from_numpy(joint_axis).float(),
921
+ 'joint_origin': torch.from_numpy(joint_origin_normalized).float(),
922
+ 'part_mask': torch.from_numpy(sampled_part_mask).float(),
923
+ 'norm_center': torch.from_numpy(center).float(),
924
+ 'norm_scale': torch.tensor(scale).float(),
925
+ 'origin_normalization_version': torch.tensor(1).long(),
926
+ }
927
+
928
+ if rotation_direction is not None:
929
+ result['rotation_direction'] = torch.from_numpy(rotation_direction).float()
930
+
931
+ if trajectory_vectors is not None:
932
+ result['trajectory_vectors'] = torch.from_numpy(trajectory_vectors).float()
933
+
934
+ # Propagate drag_trajectory if needed.
935
+ if 'drag_trajectory' in sample:
936
+ traj = (sample['drag_trajectory'] - center) / scale
937
+ result['drag_trajectory'] = torch.from_numpy(traj).float()
938
+
939
+ return result
DragMesh/dragmesh/data/dataset_utils.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shared dataset utilities for category-based data loading.
3
+ """
4
+ import sys
5
+ import os
6
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
7
+ import json
8
+ import torch
9
+ import numpy as np
10
+ from typing import Optional, List, Dict
11
+
12
+ from dragmesh.data.data_loader_v2 import GAPartNetLoaderV2, DragMeshDatasetV2
13
+ from dragmesh.utils.kpp_normalization import mesh_center_scale, normalize_points, normalize_vector
14
+ import trimesh
15
+
16
+
17
+ class FixedGAPartNetLoader(GAPartNetLoaderV2):
18
+ """Fixed loader for flat directory structure with category filtering."""
19
+
20
+ def __init__(self, dataset_root: str, categories: Optional[List[str]] = None):
21
+ self.categories = categories
22
+ super().__init__(dataset_root)
23
+
24
+ def _get_object_list(self):
25
+ """Get list of all object directories in the dataset (flat structure)."""
26
+ object_list = []
27
+ for obj_id in os.listdir(self.dataset_root):
28
+ obj_path = os.path.join(self.dataset_root, obj_id)
29
+ if not os.path.isdir(obj_path):
30
+ continue
31
+ urdf_path = os.path.join(obj_path, "mobility_annotation_gapartnet.urdf")
32
+ if not os.path.exists(urdf_path):
33
+ continue
34
+
35
+ # Check category filtering
36
+ if self.categories is not None:
37
+ meta_path = os.path.join(obj_path, "meta.json")
38
+ if os.path.exists(meta_path):
39
+ try:
40
+ with open(meta_path, 'r') as f:
41
+ meta = json.load(f)
42
+ category = meta.get('model_cat', None)
43
+ if category not in self.categories:
44
+ continue
45
+ except:
46
+ continue
47
+ else:
48
+ continue
49
+
50
+ object_list.append(obj_path)
51
+ return object_list
52
+
53
+
54
+ class FixedDragMeshDatasetV2(DragMeshDatasetV2):
55
+ """Dataset wrapper with category filtering."""
56
+
57
+ def __init__(self, dataset_root: str, num_frames: int = 16, num_points: int = 4096,
58
+ categories: Optional[List[str]] = None,
59
+ joint_selection: str = "largest_motion"):
60
+ self.loader = FixedGAPartNetLoader(dataset_root, categories=categories)
61
+ self.num_frames = num_frames
62
+ self.num_points = num_points
63
+ self.joint_selection = joint_selection
64
+
65
+
66
+ class KPPDataset(FixedDragMeshDatasetV2):
67
+ """Dataset for KPP-Net training with part_mask and joint parameters."""
68
+
69
+ def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
70
+ """
71
+ Get a training sample.
72
+ """
73
+ sample = self.loader.generate_training_sample(idx, self.num_frames, joint_selection=getattr(self, "joint_selection", "largest_motion"))
74
+
75
+ # KPP origin prediction must use an inference-reproducible frame.
76
+ # Centering at the GT joint origin makes the training label always zero.
77
+ center, scale = mesh_center_scale(sample['initial_mesh'])
78
+
79
+ mesh_normalized_verts = normalize_points(sample['initial_mesh'].vertices, center, scale)
80
+ mesh_normalized = trimesh.Trimesh(vertices=mesh_normalized_verts,
81
+ faces=sample['initial_mesh'].faces)
82
+
83
+ initial_pc, face_idx = trimesh.sample.sample_surface(mesh_normalized, self.num_points)
84
+
85
+ drag_point = normalize_points(sample['drag_point'], center, scale)
86
+ drag_vector = normalize_vector(sample['drag_vector'], scale)
87
+
88
+ joint_origin_normalized = normalize_points(sample['joint_origin'], center, scale)
89
+
90
+
91
+ # Joint type
92
+ if sample['joint_type'] == 'revolute' or sample['joint_type'] == 'continuous':
93
+ joint_type = 0
94
+ elif sample['joint_type'] == 'prismatic':
95
+ joint_type = 1
96
+ else:
97
+ joint_type = 0 # default to revolute
98
+
99
+ qr_gt = sample['qr_sequence']
100
+
101
+ if joint_type == 0:
102
+ qd_gt = sample['qd_sequence'].copy()
103
+ qd_gt = qd_gt / scale
104
+ else:
105
+ qd_gt = sample['qd_sequence'].copy()
106
+ qd_gt = qd_gt / scale
107
+
108
+ # 8) Joint axis (unchanged; normalized).
109
+ joint_axis = sample['joint_axis']
110
+ joint_axis = joint_axis / (np.linalg.norm(joint_axis) + 1e-8)
111
+
112
+ # 9) Part mask (unchanged).
113
+ original_mesh = sample['initial_mesh']
114
+ vertex_part_mask = sample['part_mask'] # [N_verts]
115
+
116
+ sampled_part_mask = np.zeros(self.num_points, dtype=np.int32)
117
+ for i, fid in enumerate(face_idx):
118
+ face_vertices = original_mesh.faces[fid]
119
+ face_mask_values = vertex_part_mask[face_vertices]
120
+ sampled_part_mask[i] = np.bincount(face_mask_values.astype(int)).argmax()
121
+
122
+
123
+ return {
124
+ 'initial_mesh': torch.from_numpy(initial_pc).float(),
125
+ 'drag_point': torch.from_numpy(drag_point).float(),
126
+ 'drag_vector': torch.from_numpy(drag_vector).float(),
127
+ 'qr_gt': torch.from_numpy(qr_gt).float(),
128
+ 'qd_gt': torch.from_numpy(qd_gt).float(),
129
+ 'joint_type': torch.tensor(joint_type).long(),
130
+ 'joint_axis': torch.from_numpy(joint_axis).float(),
131
+ 'joint_origin': torch.from_numpy(joint_origin_normalized).float(),
132
+ 'part_mask': torch.from_numpy(sampled_part_mask).float(),
133
+ 'norm_center': torch.from_numpy(center).float(),
134
+ 'norm_scale': torch.tensor(scale).float(),
135
+ 'origin_normalization_version': torch.tensor(1).long(),
136
+ }
137
+
138
+ def mesh_to_pointcloud_with_faces(self, mesh, num_points):
139
+ """Sample point cloud from mesh surface and return face indices."""
140
+ import trimesh
141
+ points, face_idx = trimesh.sample.sample_surface(mesh, num_points)
142
+ return points, face_idx
143
+
144
+ def map_face_mask_to_points(self, mesh, part_mask_vertices, face_indices):
145
+ """Map vertex-based part mask to sampled points using face indices."""
146
+ # For each sampled point (via face), get the mask value
147
+ part_mask_points = np.zeros(len(face_indices), dtype=np.float32)
148
+
149
+ for i, face_idx in enumerate(face_indices):
150
+ # Get vertices of this face
151
+ face_vertices = mesh.faces[face_idx]
152
+ # Use majority vote or first vertex mask value
153
+ face_mask_values = part_mask_vertices[face_vertices]
154
+ part_mask_points[i] = np.mean(face_mask_values) # Average mask value for this face
155
+
156
+ return part_mask_points
157
+
158
+
159
+ def load_category_config(config_path: str):
160
+ """
161
+ Load category split configuration from JSON file.
162
+
163
+ Args:
164
+ config_path: Path to category_split.json
165
+
166
+ Returns:
167
+ tuple of (train_categories, val_categories)
168
+ """
169
+ if not os.path.exists(config_path):
170
+ raise FileNotFoundError(f"Category config not found: {config_path}")
171
+
172
+ with open(config_path, 'r') as f:
173
+ category_config = json.load(f)
174
+
175
+ train_categories = category_config['train_categories']
176
+ val_categories = category_config['val_categories']
177
+
178
+ return train_categories, val_categories
179
+
180
+
181
+ def print_category_split_info(config_path: str, train_categories: List[str], val_categories: List[str]):
182
+ """Print information about category split."""
183
+ print("\n" + "="*60)
184
+ print("CATEGORY-BASED DATA SPLIT")
185
+ print("="*60)
186
+ print(f"Config loaded from: {config_path}")
187
+ print(f"Training categories ({len(train_categories)}): {train_categories}")
188
+ print(f"Validation categories ({len(val_categories)}): {val_categories}")
189
+ print("="*60 + "\n")
DragMesh/dragmesh/geometry/__init__.py ADDED
File without changes
DragMesh/dragmesh/geometry/deformation.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mesh Deformation Module using ArtGS's Dual Quaternion
3
+
4
+ This module applies predicted dual quaternion transformations to mesh vertices
5
+ to generate animated mesh sequences.
6
+ """
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import numpy as np
11
+ import trimesh
12
+ from typing import Tuple, List, Dict
13
+ from dragmesh.geometry.dual_quaternion import (
14
+ dual_quaternion_apply,
15
+ dual_quaternion_to_quaternion_translation,
16
+ quaternion_translation_apply
17
+ )
18
+
19
+
20
+ class MeshDeformationEngine:
21
+ """
22
+ Apply dual quaternion transformations to mesh vertices.
23
+ Uses ArtGS's dual_quaternion_apply for smooth articulated motion.
24
+ """
25
+
26
+ def __init__(self, device='cpu'):
27
+ self.device = device
28
+
29
+ def apply_dualquat_to_vertices(
30
+ self,
31
+ vertices: torch.Tensor,
32
+ qr: torch.Tensor,
33
+ qd: torch.Tensor,
34
+ part_mask: torch.Tensor = None
35
+ ) -> torch.Tensor:
36
+ """
37
+ Apply dual quaternion transformation to vertices.
38
+
39
+ Args:
40
+ vertices: Vertex positions [N, 3] or [B, N, 3]
41
+ qr: Rotation quaternion [4] or [B, 4]
42
+ qd: Translation quaternion [4] or [B, 4]
43
+ part_mask: Which vertices to transform [N] (0=static, 1=movable)
44
+ If None, transform all vertices
45
+
46
+ Returns:
47
+ Transformed vertices [N, 3] or [B, N, 3]
48
+ """
49
+ # Handle batched vs single input
50
+ is_batched = vertices.dim() == 3
51
+
52
+ if part_mask is None:
53
+ # Transform all vertices
54
+ deformed_vertices = dual_quaternion_apply((qr, qd), vertices)
55
+ else:
56
+ # Only transform movable vertices
57
+ if is_batched:
58
+ # Batched processing
59
+ B, N, _ = vertices.shape
60
+ deformed_vertices = vertices.clone()
61
+ movable_mask = (part_mask == 1)
62
+
63
+ for b in range(B):
64
+ movable_verts = vertices[b, movable_mask] # [M, 3]
65
+ transformed = dual_quaternion_apply((qr[b], qd[b]), movable_verts)
66
+ deformed_vertices[b, movable_mask] = transformed
67
+ else:
68
+ # Single mesh processing
69
+ deformed_vertices = vertices.clone()
70
+ movable_mask = (part_mask == 1)
71
+ movable_verts = vertices[movable_mask] # [M, 3]
72
+ transformed = dual_quaternion_apply((qr, qd), movable_verts)
73
+ deformed_vertices[movable_mask] = transformed
74
+
75
+ return deformed_vertices
76
+
77
+ def generate_mesh_sequence(
78
+ self,
79
+ vertices: torch.Tensor,
80
+ faces: torch.Tensor,
81
+ qr_sequence: torch.Tensor,
82
+ qd_sequence: torch.Tensor,
83
+ part_mask: torch.Tensor = None
84
+ ) -> List[trimesh.Trimesh]:
85
+ """
86
+ Generate animated mesh sequence from dual quaternion sequence.
87
+
88
+ Args:
89
+ vertices: Initial vertex positions [N, 3]
90
+ faces: Face indices [F, 3]
91
+ qr_sequence: Rotation quaternion sequence [T, 4]
92
+ qd_sequence: Translation quaternion sequence [T, 4]
93
+ part_mask: Which vertices are movable [N]
94
+
95
+ Returns:
96
+ List of trimesh objects [T frames]
97
+ """
98
+ num_frames = qr_sequence.shape[0]
99
+ mesh_sequence = []
100
+
101
+ vertices = vertices.to(self.device)
102
+ qr_sequence = qr_sequence.to(self.device)
103
+ qd_sequence = qd_sequence.to(self.device)
104
+ if part_mask is not None:
105
+ part_mask = part_mask.to(self.device)
106
+
107
+ for t in range(num_frames):
108
+ # Apply transformation for frame t
109
+ deformed_verts = self.apply_dualquat_to_vertices(
110
+ vertices,
111
+ qr_sequence[t],
112
+ qd_sequence[t],
113
+ part_mask
114
+ )
115
+
116
+ # Convert to numpy and create trimesh
117
+ verts_np = deformed_verts.cpu().numpy()
118
+ faces_np = faces.cpu().numpy() if torch.is_tensor(faces) else faces
119
+
120
+ mesh = trimesh.Trimesh(vertices=verts_np, faces=faces_np)
121
+ mesh_sequence.append(mesh)
122
+
123
+ return mesh_sequence
124
+
125
+ def deform_mesh_with_vae_prediction(
126
+ self,
127
+ mesh: trimesh.Trimesh,
128
+ qr_pred: torch.Tensor,
129
+ qd_pred: torch.Tensor,
130
+ part_mask: np.ndarray = None
131
+ ) -> List[trimesh.Trimesh]:
132
+ """
133
+ Deform mesh using VAE predictions.
134
+
135
+ Args:
136
+ mesh: Initial mesh (trimesh object)
137
+ qr_pred: Predicted rotation quaternions [T, 4]
138
+ qd_pred: Predicted translation quaternions [T, 4]
139
+ part_mask: Which vertices are movable [N] (numpy array)
140
+
141
+ Returns:
142
+ List of deformed meshes [T frames]
143
+ """
144
+ # Convert mesh to torch tensors
145
+ vertices = torch.from_numpy(mesh.vertices).float()
146
+ faces = torch.from_numpy(mesh.faces).long()
147
+
148
+ if part_mask is not None:
149
+ part_mask = torch.from_numpy(part_mask).long()
150
+
151
+ # Generate sequence
152
+ mesh_sequence = self.generate_mesh_sequence(
153
+ vertices, faces, qr_pred, qd_pred, part_mask
154
+ )
155
+
156
+ return mesh_sequence
157
+
158
+
159
+ def visualize_deformation(
160
+ mesh_sequence: List[trimesh.Trimesh],
161
+ output_dir: str,
162
+ prefix: str = "frame"
163
+ ):
164
+ """
165
+ Save mesh sequence as individual OBJ files.
166
+
167
+ Args:
168
+ mesh_sequence: List of trimesh objects
169
+ output_dir: Directory to save meshes
170
+ prefix: Prefix for filenames
171
+ """
172
+ import os
173
+ os.makedirs(output_dir, exist_ok=True)
174
+
175
+ for i, mesh in enumerate(mesh_sequence):
176
+ output_path = os.path.join(output_dir, f"{prefix}_{i:03d}.obj")
177
+ mesh.export(output_path)
178
+
179
+ print(f"Saved {len(mesh_sequence)} frames to {output_dir}")
180
+
181
+
182
+ def create_animation_video(
183
+ mesh_sequence: List[trimesh.Trimesh],
184
+ output_path: str,
185
+ resolution=(800, 600),
186
+ fps=10
187
+ ):
188
+ """
189
+ Create video from mesh sequence.
190
+
191
+ Args:
192
+ mesh_sequence: List of trimesh objects
193
+ output_path: Path to save video (e.g., 'animation.mp4')
194
+ resolution: Video resolution (width, height)
195
+ fps: Frames per second
196
+ """
197
+ try:
198
+ import pyrender
199
+ import imageio
200
+ import tempfile
201
+ except ImportError:
202
+ print("Warning: pyrender or imageio not installed. Cannot create video.")
203
+ print("Install with: pip install pyrender imageio[ffmpeg]")
204
+ return
205
+
206
+ # Create pyrender scene
207
+ scene = pyrender.Scene()
208
+
209
+ # Add camera and light
210
+ camera = pyrender.PerspectiveCamera(yfov=np.pi / 3.0)
211
+ camera_pose = np.array([
212
+ [1.0, 0.0, 0.0, 0.0],
213
+ [0.0, 1.0, 0.0, 0.0],
214
+ [0.0, 0.0, 1.0, 2.0],
215
+ [0.0, 0.0, 0.0, 1.0]
216
+ ])
217
+ scene.add(camera, pose=camera_pose)
218
+
219
+ light = pyrender.DirectionalLight(color=np.ones(3), intensity=3.0)
220
+ scene.add(light, pose=camera_pose)
221
+
222
+ # Render frames
223
+ renderer = pyrender.OffscreenRenderer(*resolution)
224
+ frames = []
225
+
226
+ for i, mesh in enumerate(mesh_sequence):
227
+ # Convert trimesh to pyrender mesh
228
+ mesh_pr = pyrender.Mesh.from_trimesh(mesh)
229
+
230
+ # Add mesh to scene
231
+ mesh_node = scene.add(mesh_pr)
232
+
233
+ # Render
234
+ color, _ = renderer.render(scene)
235
+ frames.append(color)
236
+
237
+ # Remove mesh for next frame
238
+ scene.remove_node(mesh_node)
239
+
240
+ # Save video
241
+ imageio.mimsave(output_path, frames, fps=fps)
242
+ print(f"Saved animation to {output_path}")
243
+
244
+ renderer.delete()
245
+
246
+
247
+ # Example usage
248
+ if __name__ == "__main__":
249
+ print("Testing Mesh Deformation Engine...")
250
+
251
+ # Create a simple test mesh (cube)
252
+ vertices = torch.tensor([
253
+ [-1, -1, -1],
254
+ [1, -1, -1],
255
+ [1, 1, -1],
256
+ [-1, 1, -1],
257
+ [-1, -1, 1],
258
+ [1, -1, 1],
259
+ [1, 1, 1],
260
+ [-1, 1, 1],
261
+ ], dtype=torch.float32)
262
+
263
+ faces = torch.tensor([
264
+ [0, 1, 2], [0, 2, 3], # Front
265
+ [4, 5, 6], [4, 6, 7], # Back
266
+ [0, 1, 5], [0, 5, 4], # Bottom
267
+ [2, 3, 7], [2, 7, 6], # Top
268
+ [0, 3, 7], [0, 7, 4], # Left
269
+ [1, 2, 6], [1, 6, 5], # Right
270
+ ])
271
+
272
+ # Part mask: top half is movable
273
+ part_mask = torch.tensor([0, 0, 0, 0, 1, 1, 1, 1], dtype=torch.long)
274
+
275
+ # Create a simple rotation sequence
276
+ num_frames = 16
277
+ angles = torch.linspace(0, np.pi / 2, num_frames)
278
+
279
+ qr_sequence = []
280
+ qd_sequence = []
281
+
282
+ for angle in angles:
283
+ # Rotation around Y axis
284
+ qr = torch.tensor([
285
+ np.cos(angle / 2),
286
+ 0,
287
+ np.sin(angle / 2),
288
+ 0
289
+ ], dtype=torch.float32)
290
+
291
+ # No translation
292
+ qd = torch.tensor([0, 0, 0, 0], dtype=torch.float32)
293
+
294
+ qr_sequence.append(qr)
295
+ qd_sequence.append(qd)
296
+
297
+ qr_sequence = torch.stack(qr_sequence)
298
+ qd_sequence = torch.stack(qd_sequence)
299
+
300
+ # Create deformation engine
301
+ engine = MeshDeformationEngine()
302
+
303
+ # Generate mesh sequence
304
+ print("\nGenerating mesh sequence...")
305
+ mesh_sequence = engine.generate_mesh_sequence(
306
+ vertices, faces, qr_sequence, qd_sequence, part_mask
307
+ )
308
+
309
+ print(f"Generated {len(mesh_sequence)} frames")
310
+ print(f"First frame vertices: {mesh_sequence[0].vertices.shape}")
311
+ print(f"Last frame vertices: {mesh_sequence[-1].vertices.shape}")
312
+
313
+ # Visualize deformation
314
+ print("\nSaving frames...")
315
+ visualize_deformation(mesh_sequence, "outputs/test_deformation", "test_cube")
316
+
317
+ print("\nTest complete!")
DragMesh/dragmesh/inference/__init__.py ADDED
File without changes
DragMesh/dragmesh/inference/inference_animation.py ADDED
@@ -0,0 +1,930 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------
2
+ # inference_animation.py
3
+ # -------------------------------------------------------------------
4
+
5
+ import sys
6
+ import os
7
+ import torch
8
+ import numpy as np
9
+ import trimesh
10
+ import argparse
11
+ from tqdm import tqdm
12
+ from difflib import get_close_matches
13
+ import tempfile
14
+ import copy
15
+
16
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
17
+ import torch.nn.functional as F
18
+ import math
19
+
20
+ from dragmesh.models.model_v2 import DualQuaternionVAE
21
+ from dragmesh.data.data_loader_v2 import GAPartNetLoaderV2
22
+ from dragmesh.geometry.dual_quaternion import dual_quaternion_apply, quaternion_to_axis_angle, quaternion_multiply, quaternion_conjugate
23
+
24
+ # --- Offscreen rendering (headless fallback) ---
25
+ _OFFSCREEN_RENDERING_BROKEN = False
26
+
27
+ def _maybe_set_headless_opengl_platform():
28
+ """
29
+ In headless environments (no DISPLAY), `pyrender` may default to `pyglet` and raise
30
+ `NoSuchDisplayException`. We set `PYOPENGL_PLATFORM` before importing pyrender to
31
+ prefer EGL (GPU) and fall back to OSMesa (software).
32
+ """
33
+ if os.environ.get("DISPLAY"):
34
+ return
35
+ if os.environ.get("PYOPENGL_PLATFORM"):
36
+ return
37
+ # Prefer EGL (common on GPU servers); fall back to OSMesa (software rendering).
38
+ os.environ["PYOPENGL_PLATFORM"] = "egl"
39
+
40
+ # --- glTF animation support ---
41
+ try:
42
+ import pygltflib
43
+ from pygltflib import GLTF2
44
+ except ImportError:
45
+ print("\n--- Warning: pygltflib not installed ---")
46
+ print("Skipping animated GLB export. Install with: pip install pygltflib")
47
+ pygltflib = None
48
+
49
+ # --- Helpers ---
50
+ def project_rotation_to_axis(quaternion, target_axis):
51
+ """Project a quaternion to a target axis (PyTorch tensor implementation)."""
52
+ target_axis = target_axis.to(quaternion.device)
53
+ angle = 2 * torch.acos(torch.clamp(quaternion[..., 0:1].abs(), -1.0, 1.0))
54
+ target_axis_normalized = F.normalize(target_axis, p=2, dim=-1)
55
+ half_angle = angle / 2.0
56
+ projected_quaternion = torch.cat([
57
+ torch.cos(half_angle),
58
+ target_axis_normalized * torch.sin(half_angle)
59
+ ], dim=-1)
60
+ projected_quaternion = F.normalize(projected_quaternion, p=2, dim=-1)
61
+ return projected_quaternion
62
+
63
+ def _nlerp_quaternion_sequence(q_start: torch.Tensor, q_end: torch.Tensor, t_values: torch.Tensor) -> torch.Tensor:
64
+ """
65
+ Normalized linear interpolation (NLERP) for quaternions.
66
+
67
+ This is used to produce a "single interaction" rotation trajectory (no cumulative spinning).
68
+ Args:
69
+ q_start/q_end: [4] (wxyz)
70
+ t_values: [T]
71
+ Returns:
72
+ [T, 4]
73
+ """
74
+ # Handle double cover: always take the shortest arc.
75
+ dot = torch.dot(q_start, q_end)
76
+ if dot < 0.0:
77
+ q_end = -q_end
78
+ q = (1.0 - t_values.unsqueeze(-1)) * q_start.unsqueeze(0) + t_values.unsqueeze(-1) * q_end.unsqueeze(0)
79
+ return F.normalize(q, p=2, dim=-1)
80
+
81
+ def _make_loop_t_values(num_frames: int, loop_mode: str, device: torch.device) -> torch.Tensor:
82
+ """
83
+ loop_mode:
84
+ - once: 0->1
85
+ - pingpong: 0->1->0 (seamless looping in common viewers; avoids continuous spinning)
86
+ """
87
+ if num_frames <= 1:
88
+ return torch.zeros((num_frames,), device=device)
89
+ if loop_mode == "pingpong":
90
+ forward_steps = num_frames // 2 + 1
91
+ backward_steps = num_frames - forward_steps
92
+ t_fwd = torch.linspace(0.0, 1.0, steps=forward_steps, device=device)
93
+ if backward_steps <= 0:
94
+ return t_fwd
95
+ t_bwd_full = torch.linspace(1.0, 0.0, steps=backward_steps + 1, device=device)
96
+ t_bwd = t_bwd_full[1:] # drop the duplicated 1.0
97
+ return torch.cat([t_fwd, t_bwd], dim=0)
98
+ # default: once
99
+ return torch.linspace(0.0, 1.0, steps=num_frames, device=device)
100
+
101
+ # --- Rendering 1: GIF ---
102
+ def create_gif(mesh_sequence, output_path, resolution=(600, 600), fps=15):
103
+ global _OFFSCREEN_RENDERING_BROKEN
104
+ if _OFFSCREEN_RENDERING_BROKEN:
105
+ return
106
+ try:
107
+ _maybe_set_headless_opengl_platform()
108
+ import pyrender
109
+ import imageio
110
+ except ImportError:
111
+ return
112
+ except Exception as e:
113
+ _OFFSCREEN_RENDERING_BROKEN = True
114
+ print(f"[WARN] Offscreen renderer init failed (headless?): {type(e).__name__}: {e}")
115
+ print(" Tips: (1) export GLB (install pygltflib), (2) set PYOPENGL_PLATFORM=egl/osmesa, "
116
+ "(3) run on a machine with a display.")
117
+ return
118
+
119
+ print(f"Generating GIF: {output_path}")
120
+ if not mesh_sequence: return
121
+ renderer = None
122
+ try:
123
+ scene = pyrender.Scene(ambient_light=[0.1, 0.1, 0.3], bg_color=[255, 255, 255])
124
+ first_mesh = mesh_sequence[0]
125
+
126
+ camera_pose = np.eye(4)
127
+ zoom = np.max(first_mesh.extents) * 2.5
128
+ camera_pose[2, 3] = zoom
129
+
130
+ angle_y = math.radians(30)
131
+ R_y = np.array([[math.cos(angle_y), 0, math.sin(angle_y), 0], [0, 1, 0, 0], [-math.sin(angle_y), 0, math.cos(angle_y), 0], [0, 0, 0, 1]])
132
+ angle_x = math.radians(-30)
133
+ R_x = np.array([[1, 0, 0, 0], [0, math.cos(angle_x), -math.sin(angle_x), 0], [0, math.sin(angle_x), math.cos(angle_x), 0], [0, 0, 0, 1]])
134
+ camera_pose = R_x @ R_y @ camera_pose
135
+
136
+ camera = pyrender.PerspectiveCamera(yfov=np.pi / 3.0)
137
+ scene.add(camera, pose=camera_pose)
138
+ scene.add(pyrender.DirectionalLight(color=[1, 1, 1], intensity=2.0), pose=camera_pose)
139
+ renderer = pyrender.OffscreenRenderer(*resolution)
140
+ frames = []
141
+
142
+ for mesh in mesh_sequence:
143
+ render_mesh = pyrender.Mesh.from_trimesh(mesh, smooth=True)
144
+ mesh_node = scene.add(render_mesh)
145
+ color, _ = renderer.render(scene)
146
+ frames.append(color)
147
+ scene.remove_node(mesh_node)
148
+
149
+ imageio.mimsave(output_path, frames, fps=fps)
150
+ except Exception as e:
151
+ _OFFSCREEN_RENDERING_BROKEN = True
152
+ print(f"[WARN] GIF render failed, skipping rendering. {type(e).__name__}: {e}")
153
+ finally:
154
+ try:
155
+ if renderer is not None:
156
+ renderer.delete()
157
+ except Exception:
158
+ pass
159
+
160
+ # --- Rendering 2: MP4 ---
161
+ def create_animation_video_local(mesh_sequence, output_path, resolution=(600, 600), fps=15):
162
+ global _OFFSCREEN_RENDERING_BROKEN
163
+ if _OFFSCREEN_RENDERING_BROKEN:
164
+ return
165
+ try:
166
+ _maybe_set_headless_opengl_platform()
167
+ import pyrender
168
+ import imageio
169
+ except ImportError:
170
+ return
171
+ except Exception as e:
172
+ _OFFSCREEN_RENDERING_BROKEN = True
173
+ print(f"[WARN] Offscreen renderer init failed (headless?): {type(e).__name__}: {e}")
174
+ print(" Tips: (1) export GLB (install pygltflib), (2) set PYOPENGL_PLATFORM=egl/osmesa, "
175
+ "(3) run on a machine with a display.")
176
+ return
177
+
178
+ print(f"Generating MP4: {output_path}")
179
+ if not mesh_sequence: return
180
+ renderer = None
181
+ try:
182
+ scene = pyrender.Scene(ambient_light=[0.1, 0.1, 0.3], bg_color=[255, 255, 255])
183
+ first_mesh = mesh_sequence[0]
184
+
185
+ camera_pose = np.eye(4)
186
+ zoom = np.max(first_mesh.extents) * 2.5
187
+ camera_pose[2, 3] = zoom
188
+
189
+ angle_y = math.radians(30)
190
+ R_y = np.array([[math.cos(angle_y), 0, math.sin(angle_y), 0], [0, 1, 0, 0], [-math.sin(angle_y), 0, math.cos(angle_y), 0], [0, 0, 0, 1]])
191
+ angle_x = math.radians(-30)
192
+ R_x = np.array([[1, 0, 0, 0], [0, math.cos(angle_x), -math.sin(angle_x), 0], [0, math.sin(angle_x), math.cos(angle_x), 0], [0, 0, 0, 1]])
193
+ camera_pose = R_x @ R_y @ camera_pose
194
+
195
+ camera = pyrender.PerspectiveCamera(yfov=np.pi / 3.0)
196
+ scene.add(camera, pose=camera_pose)
197
+ scene.add(pyrender.DirectionalLight(color=[1, 1, 1], intensity=2.0), pose=camera_pose)
198
+ renderer = pyrender.OffscreenRenderer(*resolution)
199
+ frames = []
200
+
201
+ for mesh in mesh_sequence:
202
+ render_mesh = pyrender.Mesh.from_trimesh(mesh, smooth=True)
203
+ mesh_node = scene.add(render_mesh)
204
+ color, _ = renderer.render(scene)
205
+ frames.append(color)
206
+ scene.remove_node(mesh_node)
207
+
208
+ # MP4 export relies on the imageio-ffmpeg backend; keep this best-effort (do not fail inference).
209
+ imageio.mimsave(output_path, frames, fps=fps)
210
+ except Exception as e:
211
+ _OFFSCREEN_RENDERING_BROKEN = True
212
+ print(f"[WARN] MP4 render failed, skipping rendering. {type(e).__name__}: {e}")
213
+ print(" Continuing inference outputs. For video/GIF, run with DISPLAY or configure EGL/OSMesa.")
214
+ finally:
215
+ try:
216
+ if renderer is not None:
217
+ renderer.delete()
218
+ except Exception:
219
+ pass
220
+
221
+
222
+ # --- Core: export an animated GLB ---
223
+ def export_animated_glb(initial_mesh, part_mask_np, qr_seq_tensor, qd_seq_tensor,
224
+ joint_origin_norm_tensor, scale, center, output_path, fps=10):
225
+ """
226
+ Export an animated GLB with translation/rotation tracks.
227
+ """
228
+ if pygltflib is None:
229
+ return
230
+
231
+ print(f"Generating Animated GLB: {output_path}")
232
+
233
+ def _pad_to_4bytes(blob: bytearray) -> None:
234
+ """glTF bufferView requires 4-byte alignment (GLB viewers often rely on this)."""
235
+ pad = (-len(blob)) % 4
236
+ if pad:
237
+ blob.extend(b"\x00" * pad)
238
+
239
+ # 1) De-normalize joint origin back to world space.
240
+ real_origin = joint_origin_norm_tensor.cpu().numpy() * scale + center
241
+
242
+ # 2) Split the mesh into static vs moving parts (preserve materials via trimesh submesh).
243
+ try:
244
+ # All faces
245
+ faces = initial_mesh.faces
246
+ vertex_mask = part_mask_np.astype(bool)
247
+
248
+ # Face assignment: a face is moving iff all its vertices are marked movable.
249
+ # This heuristic works well for rigid part segmentations (e.g., GAPartNet).
250
+ face_mask = vertex_mask[faces].all(axis=1)
251
+
252
+ moving_face_ids = np.where(face_mask)[0]
253
+ static_face_ids = np.where(~face_mask)[0]
254
+
255
+ # Degenerate masks (all-moving or all-static): avoid empty submeshes.
256
+ if moving_face_ids.size == 0 or static_face_ids.size == 0:
257
+ initial_mesh.export(output_path)
258
+ return
259
+
260
+ # trimesh.submesh expects face index lists, not boolean masks.
261
+ mesh_moving = initial_mesh.submesh([moving_face_ids], append=True)
262
+ mesh_static = initial_mesh.submesh([static_face_ids], append=True)
263
+
264
+ # Name nodes for debugging.
265
+ mesh_moving.name = "moving_part"
266
+ mesh_static.name = "static_part"
267
+
268
+ except Exception as e:
269
+ print(f"Error splitting mesh for GLB: {e}")
270
+ # Fallback: export a static GLB if splitting fails.
271
+ initial_mesh.export(output_path)
272
+ return
273
+
274
+ # 3) Pivot adjustment:
275
+ # A) translate moving vertices so the joint origin becomes (0, 0, 0) in its local frame
276
+ # B) set the moving node translation back to the joint origin in world space
277
+
278
+ mesh_moving.vertices -= real_origin
279
+
280
+ # 4) Build a trimesh.Scene and export a base GLB (trimesh handles material packaging).
281
+ scene = trimesh.Scene()
282
+ scene.add_geometry(mesh_static, node_name='static_node')
283
+
284
+ # Initial transform: translate the moving node to the joint pivot.
285
+ transform_matrix = np.eye(4)
286
+ transform_matrix[:3, 3] = real_origin
287
+ scene.add_geometry(mesh_moving, node_name='moving_node', transform=transform_matrix)
288
+
289
+ # Export a temporary GLB (trimesh performs binary conversion and material handling).
290
+ fd, temp_glb_path = tempfile.mkstemp(suffix='.glb')
291
+ os.close(fd)
292
+ scene.export(temp_glb_path)
293
+
294
+ # 5) Inject animation data via pygltflib.
295
+ gltf = GLTF2().load(temp_glb_path)
296
+
297
+ # Locate the moving node index.
298
+ moving_node_idx = -1
299
+ for i, node in enumerate(gltf.nodes):
300
+ if node.name == 'moving_node':
301
+ moving_node_idx = i
302
+ break
303
+
304
+ # Fallback: trimesh may rename nodes; the last node is typically the last added.
305
+ if moving_node_idx == -1:
306
+ moving_node_idx = len(gltf.nodes) - 1
307
+
308
+ # --- Keyframe data ---
309
+ num_frames = qr_seq_tensor.shape[0]
310
+ times = (np.arange(num_frames, dtype=np.float32) / float(fps)).astype(np.float32)
311
+
312
+ # Force TRS on the moving node. Some exporters write node.matrix, which can cause
313
+ # translation/rotation tracks to be ignored in certain viewers.
314
+ try:
315
+ node = gltf.nodes[moving_node_idx]
316
+ if getattr(node, "matrix", None):
317
+ node.matrix = None
318
+ node.translation = real_origin.astype(np.float32).tolist()
319
+ if node.rotation is None:
320
+ node.rotation = [0.0, 0.0, 0.0, 1.0]
321
+ if node.scale is None:
322
+ node.scale = [1.0, 1.0, 1.0]
323
+ except Exception:
324
+ pass
325
+
326
+ # A) Rotation: DualQuaternion real part -> glTF quaternion.
327
+ # PyTorch: [w, x, y, z] -> glTF: [x, y, z, w]
328
+ qr_seq = qr_seq_tensor.detach().cpu().numpy().astype(np.float32)
329
+ # Normalize to avoid non-unit quaternions (some viewers reject them).
330
+ qr_norm = np.linalg.norm(qr_seq, axis=1, keepdims=True)
331
+ qr_norm = np.where(qr_norm < 1e-8, 1.0, qr_norm)
332
+ qr_seq = qr_seq / qr_norm
333
+ rotations = np.zeros((num_frames, 4), dtype=np.float32)
334
+ rotations[:, 0] = qr_seq[:, 1] # x
335
+ rotations[:, 1] = qr_seq[:, 2] # y
336
+ rotations[:, 2] = qr_seq[:, 3] # z
337
+ rotations[:, 3] = qr_seq[:, 0] # w
338
+
339
+ # B) Translation:
340
+ # The node is already positioned at `real_origin`. The DQ translation is an offset
341
+ # in normalized space, so per-frame translation is: real_origin + t * scale.
342
+
343
+ qr_conj = quaternion_conjugate(qr_seq_tensor)
344
+ t_q = 2.0 * quaternion_multiply(qd_seq_tensor, qr_conj)
345
+ t_vec_norm = t_q[:, 1:].cpu().numpy() # [N, 3]
346
+ t_vec_real = t_vec_norm * scale
347
+
348
+ translations = np.zeros((num_frames, 3), dtype=np.float32)
349
+ for i in range(num_frames):
350
+ translations[i] = real_origin + t_vec_real[i]
351
+
352
+ # --- Write binary buffer ---
353
+ blob = bytearray(gltf.binary_blob())
354
+ _pad_to_4bytes(blob)
355
+
356
+ # 1. Times Input
357
+ times_bytes = times.tobytes()
358
+ times_offset = len(blob)
359
+ blob.extend(times_bytes)
360
+ _pad_to_4bytes(blob)
361
+ times_view_idx = len(gltf.bufferViews)
362
+ gltf.bufferViews.append(pygltflib.BufferView(buffer=0, byteOffset=times_offset, byteLength=len(times_bytes)))
363
+ times_accessor_idx = len(gltf.accessors)
364
+ gltf.accessors.append(pygltflib.Accessor(
365
+ bufferView=times_view_idx, componentType=pygltflib.FLOAT, count=num_frames, type=pygltflib.SCALAR,
366
+ min=[float(times.min())], max=[float(times.max())]
367
+ ))
368
+
369
+ # 2. Translations Output
370
+ trans_bytes = translations.tobytes()
371
+ trans_offset = len(blob)
372
+ blob.extend(trans_bytes)
373
+ _pad_to_4bytes(blob)
374
+ trans_view_idx = len(gltf.bufferViews)
375
+ gltf.bufferViews.append(pygltflib.BufferView(buffer=0, byteOffset=trans_offset, byteLength=len(trans_bytes)))
376
+ trans_accessor_idx = len(gltf.accessors)
377
+ gltf.accessors.append(pygltflib.Accessor(
378
+ bufferView=trans_view_idx, componentType=pygltflib.FLOAT, count=num_frames, type=pygltflib.VEC3,
379
+ min=translations.min(axis=0).tolist(), max=translations.max(axis=0).tolist()
380
+ ))
381
+
382
+ # 3. Rotations Output
383
+ rot_bytes = rotations.tobytes()
384
+ rot_offset = len(blob)
385
+ blob.extend(rot_bytes)
386
+ _pad_to_4bytes(blob)
387
+ rot_view_idx = len(gltf.bufferViews)
388
+ gltf.bufferViews.append(pygltflib.BufferView(buffer=0, byteOffset=rot_offset, byteLength=len(rot_bytes)))
389
+ rot_accessor_idx = len(gltf.accessors)
390
+ gltf.accessors.append(pygltflib.Accessor(
391
+ bufferView=rot_view_idx, componentType=pygltflib.FLOAT, count=num_frames, type=pygltflib.VEC4
392
+ ))
393
+
394
+ # Update blob length.
395
+ gltf.set_binary_blob(blob)
396
+ try:
397
+ if gltf.buffers and len(gltf.buffers) > 0:
398
+ gltf.buffers[0].byteLength = len(blob)
399
+ except Exception:
400
+ pass
401
+
402
+ # --- Create animation object ---
403
+ anim = pygltflib.Animation(name="Interaction")
404
+
405
+ # Translation Channel
406
+ anim.samplers.append(pygltflib.AnimationSampler(input=times_accessor_idx, output=trans_accessor_idx, interpolation=pygltflib.LINEAR))
407
+ anim.channels.append(pygltflib.AnimationChannel(sampler=0, target=pygltflib.AnimationChannelTarget(node=moving_node_idx, path="translation")))
408
+
409
+ # Rotation Channel
410
+ anim.samplers.append(pygltflib.AnimationSampler(input=times_accessor_idx, output=rot_accessor_idx, interpolation=pygltflib.LINEAR))
411
+ anim.channels.append(pygltflib.AnimationChannel(sampler=1, target=pygltflib.AnimationChannelTarget(node=moving_node_idx, path="rotation")))
412
+
413
+ gltf.animations.append(anim)
414
+
415
+ # Save final GLB.
416
+ gltf.save(output_path)
417
+
418
+ # Cleanup.
419
+ if os.path.exists(temp_glb_path):
420
+ os.remove(temp_glb_path)
421
+
422
+ print(f" Animated GLB saved: {output_path}")
423
+
424
+
425
+ # --- Loader ---
426
+ class FixedGAPartNetLoader(GAPartNetLoaderV2):
427
+ """Loader for a flat directory layout (one object per subfolder)."""
428
+ def _get_object_list(self):
429
+ object_list = []
430
+ if not os.path.isdir(self.dataset_root):
431
+ print(f"Error: dataset root does not exist: '{self.dataset_root}'")
432
+ return object_list
433
+ for obj_id in os.listdir(self.dataset_root):
434
+ obj_path = os.path.join(self.dataset_root, obj_id)
435
+ if not os.path.isdir(obj_path):
436
+ continue
437
+ urdf_path = os.path.join(obj_path, "mobility_annotation_gapartnet.urdf")
438
+ if os.path.exists(urdf_path):
439
+ object_list.append(obj_path)
440
+ return sorted(object_list)
441
+
442
+
443
+ def load_model(checkpoint_path, device, args):
444
+ """Load the VAE model from a checkpoint."""
445
+ try:
446
+ checkpoint = torch.load(checkpoint_path, map_location='cpu')
447
+ except Exception as e:
448
+ print(f"Error: unable to load checkpoint: {e}")
449
+ return None, 16
450
+
451
+ if 'model_state_dict' not in checkpoint:
452
+ print("Error: checkpoint is missing 'model_state_dict'.")
453
+ return None, 16
454
+
455
+ model_state_dict = checkpoint['model_state_dict']
456
+ config = checkpoint.get('config', {})
457
+
458
+ latent_dim = config.get('latent_dim', args.latent_dim)
459
+ num_frames = args.num_frames if args.num_frames is not None else config.get('num_frames', 16)
460
+ transformer_layers = config.get('transformer_layers', args.transformer_layers)
461
+ transformer_heads = config.get('transformer_heads', args.transformer_heads)
462
+
463
+ print(f"\n=== Initializing VAE Model ===")
464
+ print(f" Info: layers={transformer_layers}, heads={transformer_heads}, latent={latent_dim}")
465
+
466
+ model = DualQuaternionVAE(
467
+ latent_dim=latent_dim,
468
+ num_frames=num_frames,
469
+ transformer_layers=transformer_layers,
470
+ transformer_heads=transformer_heads
471
+ ).to(device)
472
+
473
+ from collections import OrderedDict
474
+ new_state_dict = OrderedDict()
475
+ for k, v in model_state_dict.items():
476
+ if k.startswith('module.'):
477
+ name = k[7:]
478
+ new_state_dict[name] = v
479
+ else:
480
+ new_state_dict[k] = v
481
+
482
+ try:
483
+ model.load_state_dict(new_state_dict, strict=True)
484
+ print(f" Loaded with strict=True.")
485
+ except RuntimeError as e:
486
+ print(f"Warning: Strict load failed, trying loose load. Error: {str(e)[:100]}...")
487
+ model.load_state_dict(new_state_dict, strict=False)
488
+
489
+ model.eval()
490
+ return model, num_frames
491
+
492
+
493
+ def run_vae_diversity_test(model, loader, sample_idx, device, output_dir, num_frames, num_samples_to_gen, force_rotation=False, fps: float = 5.0, loop_mode: str = "pingpong"):
494
+ """
495
+ Run VAE sampling for a single input condition and export animations (GLB/GIF/MP4).
496
+ """
497
+ print(f"\n{'='*60}\nRunning VAE Diversity Test on sample index {sample_idx}\n{'='*60}\n")
498
+ try:
499
+ fps = float(fps)
500
+ except Exception:
501
+ fps = 5.0
502
+ if fps <= 0:
503
+ fps = 5.0
504
+ if loop_mode not in ["once", "pingpong"]:
505
+ loop_mode = "pingpong"
506
+
507
+ sample = loader.generate_training_sample(sample_idx, num_frames=num_frames)
508
+ if sample is None:
509
+ print(f"Error: unable to generate a valid sample for index={sample_idx}.")
510
+ return
511
+
512
+ # --- 1) Prepare inputs (normalization) ---
513
+ initial_mesh = sample['initial_mesh']
514
+ vertex_part_mask = sample['part_mask']
515
+
516
+ bounds = initial_mesh.bounds
517
+ center = (bounds[0] + bounds[1]) / 2.0
518
+ scale = (bounds[1] - bounds[0]).max()
519
+ if scale < 1e-6: scale = 1.0
520
+
521
+ initial_mesh_normalized = initial_mesh.copy()
522
+ initial_mesh_normalized.vertices = (initial_mesh_normalized.vertices - center) / scale
523
+
524
+ initial_pc, face_indices = trimesh.sample.sample_surface(initial_mesh_normalized, 4096)
525
+
526
+ sampled_part_mask_np = np.zeros(4096, dtype=np.float32)
527
+ for i, fid in enumerate(face_indices):
528
+ face_vertices = initial_mesh.faces[fid]
529
+ face_mask_values = vertex_part_mask[face_vertices]
530
+ sampled_part_mask_np[i] = np.bincount(face_mask_values.astype(int)).argmax()
531
+
532
+ part_mask_bool_idx_torch = torch.from_numpy(vertex_part_mask).bool().to(device)
533
+
534
+ # --- 2) Prepare ground-truth conditions ---
535
+ drag_point_norm = (sample['drag_point'] - center) / scale
536
+ drag_vector_norm = sample['drag_vector'] / scale
537
+ joint_type_str = sample['joint_type']
538
+
539
+ joint_type = 0 if joint_type_str in ['revolute', 'continuous'] else 1
540
+ if force_rotation:
541
+ joint_type = 0
542
+ print("*** Forcing rotation mode (joint_type=0) ***")
543
+
544
+ joint_axis_gt = sample['joint_axis']
545
+ joint_origin_gt_norm = (sample['joint_origin'] - center) / scale
546
+
547
+ rotation_direction_gt = sample.get('rotation_direction')
548
+ trajectory_vectors_gt = sample.get('trajectory_vectors')
549
+ drag_trajectory_gt = sample.get('drag_trajectory')
550
+
551
+ # --- 3) Tensorize ---
552
+ pc_tensor = torch.from_numpy(initial_pc).float().unsqueeze(0).to(device)
553
+ part_mask_tensor = torch.from_numpy(sampled_part_mask_np).float().unsqueeze(0).to(device)
554
+ drag_point_tensor = torch.from_numpy(drag_point_norm).float().unsqueeze(0).to(device)
555
+ drag_vector_tensor = torch.from_numpy(drag_vector_norm).float().unsqueeze(0).to(device)
556
+ joint_type_tensor = torch.tensor([joint_type], dtype=torch.long).to(device)
557
+ joint_axis_tensor = torch.from_numpy(joint_axis_gt).float().unsqueeze(0).to(device)
558
+ joint_origin_tensor = torch.from_numpy(joint_origin_gt_norm).float().unsqueeze(0).to(device)
559
+
560
+ rotation_direction_tensor = None
561
+ if rotation_direction_gt is not None:
562
+ rotation_direction_tensor = torch.from_numpy(rotation_direction_gt).float().unsqueeze(0).to(device)
563
+ trajectory_vectors_tensor = None
564
+ if trajectory_vectors_gt is not None:
565
+ trajectory_vectors_tensor = torch.from_numpy(trajectory_vectors_gt).float().unsqueeze(0).to(device)
566
+ drag_trajectory_tensor = None
567
+
568
+ # --- 4) VAE encoder ---
569
+ print("Running model ENCODER...")
570
+ with torch.no_grad():
571
+ combined_condition_feat, joint_feat = model.encode_features(
572
+ mesh=pc_tensor,
573
+ part_mask=part_mask_tensor,
574
+ drag_point=drag_point_tensor,
575
+ drag_vector=drag_vector_tensor,
576
+ joint_type=joint_type_tensor,
577
+ joint_axis=joint_axis_tensor,
578
+ joint_origin=joint_origin_tensor,
579
+ rotation_direction=rotation_direction_tensor,
580
+ trajectory_vectors=trajectory_vectors_tensor,
581
+ drag_trajectory=drag_trajectory_tensor
582
+ )
583
+ mu = model.fc_mu(combined_condition_feat)
584
+ logvar = model.fc_logvar(combined_condition_feat)
585
+
586
+ # --- 5) Output directory ---
587
+ chosen_id = os.path.basename(loader.object_list[sample_idx])
588
+ output_dir_id = os.path.join(output_dir, chosen_id)
589
+ os.makedirs(output_dir_id, exist_ok=True)
590
+
591
+ # Export the static initial mesh as a reference.
592
+ try:
593
+ initial_mesh.export(os.path.join(output_dir_id, 'initial_static.glb'))
594
+ except:
595
+ pass
596
+
597
+ # --- 6) VAE decoder (multi-sample) ---
598
+ print(f"\nRunning model DECODER ({num_samples_to_gen} times)...")
599
+
600
+ for s_idx in range(num_samples_to_gen):
601
+ print(f"--- Sample {s_idx+1}/{num_samples_to_gen} ---")
602
+
603
+ with torch.no_grad():
604
+ if s_idx == 0 and num_samples_to_gen > 1:
605
+ z = mu
606
+ else:
607
+ z = model.reparameterize(mu, logvar)
608
+
609
+ pred_qr_seq, pred_qd_seq = model.decode(z, joint_feat, joint_axis_tensor, joint_type_tensor)
610
+
611
+ pred_qr_seq = pred_qr_seq.squeeze(0)
612
+ pred_qd_seq = pred_qd_seq.squeeze(0)
613
+
614
+ # --- 7) Apply hard constraints & build a single-interaction trajectory ---
615
+ if joint_type == 0: # rotation
616
+ pred_qd_seq = torch.zeros_like(pred_qd_seq)
617
+ joint_axis_expanded = joint_axis_tensor.expand(pred_qr_seq.shape[0], -1)
618
+ pred_qr_seq = project_rotation_to_axis(pred_qr_seq, joint_axis_expanded)
619
+
620
+ elif joint_type == 1: # translation
621
+ identity_qr = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device)
622
+ pred_qr_seq = identity_qr.unsqueeze(0).expand(pred_qr_seq.shape[0], -1)
623
+
624
+ # Project translation onto the joint axis.
625
+ pred_qr_conj = quaternion_conjugate(pred_qr_seq)
626
+ pred_t_q = 2.0 * quaternion_multiply(pred_qd_seq, pred_qr_conj)
627
+ pred_t_vec = pred_t_q[..., 1:]
628
+
629
+ axis_vec = joint_axis_tensor.squeeze(0)
630
+ dot_prod = torch.sum(pred_t_vec * axis_vec, dim=-1, keepdim=True)
631
+ t_parallel = dot_prod * axis_vec
632
+ pred_qd_seq = torch.cat([torch.zeros_like(pred_t_vec[..., 0:1]), t_parallel], dim=-1) * 0.5
633
+
634
+ # --- Generate a "single interaction" trajectory (avoid cumulative spinning) ---
635
+ t_values = _make_loop_t_values(num_frames, loop_mode=loop_mode, device=device)
636
+ if joint_type == 0: # Rotation: Identity -> final pose (NLERP)
637
+ qr_start = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=pred_qr_seq.dtype)
638
+ qr_final = pred_qr_seq[-1].clone()
639
+ pred_qr_seq = _nlerp_quaternion_sequence(qr_start, qr_final, t_values)
640
+ pred_qd_seq = torch.zeros((num_frames, 4), device=device, dtype=pred_qd_seq.dtype)
641
+ else: # Translation: Identity -> final translation (LERP)
642
+ qr_start = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=pred_qr_seq.dtype)
643
+ qd_start = torch.tensor([0.0, 0.0, 0.0, 0.0], device=device, dtype=pred_qd_seq.dtype)
644
+ qr_final = qr_start
645
+ qd_final = pred_qd_seq[-1].clone()
646
+ # Preserve the original sign convention (translation direction may be dataset/viewer dependent).
647
+ qd_final = -qd_final
648
+ pred_qr_seq = qr_start.unsqueeze(0).expand(num_frames, -1)
649
+ pred_qd_seq = (1.0 - t_values.unsqueeze(-1)) * qd_start.unsqueeze(0) + t_values.unsqueeze(-1) * qd_final.unsqueeze(0)
650
+
651
+ # --- 8) Render video & GIF (best-effort) ---
652
+ base_output_path = os.path.join(output_dir_id, f'predicted_z_{s_idx}')
653
+
654
+ pred_mesh_sequence = []
655
+
656
+ # Precompute the mesh sequence for rendering.
657
+ joint_origin_t = joint_origin_tensor.squeeze(0)
658
+ movable_verts = verts_normalized_torch = torch.from_numpy(initial_mesh_normalized.vertices).float().to(device)
659
+ movable_verts_shifted = movable_verts - joint_origin_t # shift in joint frame (mask applied later)
660
+
661
+ for i in range(num_frames):
662
+ qr = pred_qr_seq[i]
663
+ qd = pred_qd_seq[i]
664
+
665
+ # Apply dual-quaternion transform to the movable part only.
666
+ # 1) gather movable vertices
667
+ current_movable_verts = movable_verts[part_mask_bool_idx_torch]
668
+ current_movable_verts_shifted = current_movable_verts - joint_origin_t
669
+
670
+ # 2) transform
671
+ transformed_movable = dual_quaternion_apply((qr, qd), current_movable_verts_shifted)
672
+ transformed_movable = transformed_movable + joint_origin_t
673
+
674
+ # 3) scatter back to the full mesh
675
+ deformed_verts = movable_verts.clone()
676
+ deformed_verts[part_mask_bool_idx_torch] = transformed_movable
677
+
678
+ # 4) de-normalize to world scale
679
+ denormalized_verts = deformed_verts.cpu().numpy() * scale + center
680
+
681
+ # 5) build a mesh while preserving materials
682
+ pred_mesh = trimesh.Trimesh(vertices=denormalized_verts, faces=initial_mesh.faces, process=False)
683
+ pred_mesh.visual = initial_mesh.visual
684
+ pred_mesh_sequence.append(pred_mesh)
685
+
686
+ # Render video/GIF. Smaller fps -> slower playback. pingpong is more suitable for looping viewers.
687
+ create_animation_video_local(pred_mesh_sequence, base_output_path + '.mp4', fps=fps)
688
+ create_gif(pred_mesh_sequence, base_output_path + '.gif', fps=fps)
689
+
690
+ # --- 9) Export a single animated GLB (no per-frame OBJ export) ---
691
+ if pygltflib is not None:
692
+ export_animated_glb(
693
+ initial_mesh=initial_mesh, # original mesh (with materials)
694
+ part_mask_np=vertex_part_mask, # vertex segmentation mask
695
+ qr_seq_tensor=pred_qr_seq, # predicted rotation sequence
696
+ qd_seq_tensor=pred_qd_seq, # predicted translation (DQ) sequence
697
+ joint_origin_norm_tensor=joint_origin_tensor.squeeze(0), # normalized joint origin
698
+ scale=scale,
699
+ center=center,
700
+ output_path=base_output_path + '.glb',
701
+ fps=fps
702
+ )
703
+
704
+ print(f"\n{'='*60}\n VAE Diversity Test complete! Output saved to: {output_dir_id}\n{'='*60}")
705
+
706
+
707
+ # --- Arguments ---
708
+ def parse_args():
709
+ parser = argparse.ArgumentParser(description='VAE Animation Inference')
710
+ parser.add_argument('--dataset_root', type=str, required=True)
711
+ parser.add_argument('--checkpoint', type=str, required=True)
712
+ parser.add_argument('--sample_id', type=str, required=True)
713
+ parser.add_argument('--output_dir', type=str, default='results_animation_test')
714
+ parser.add_argument('--num_samples', type=int, default=1)
715
+ parser.add_argument('--force_rotation', action='store_true')
716
+ parser.add_argument('--latent_dim', type=int, default=256)
717
+ parser.add_argument('--num_frames', type=int, default=None)
718
+ # Playback FPS: smaller -> slower (affects MP4/GIF and GLB animation timeline).
719
+ parser.add_argument('--fps', type=float, default=5.0, help='animation playback fps (smaller = slower)')
720
+ parser.add_argument('--loop_mode', type=str, default='pingpong', choices=['once', 'pingpong'],
721
+ help='once: 0->1; pingpong: 0->1->0 (better for default looping players)')
722
+ parser.add_argument('--transformer_layers', type=int, default=4)
723
+ parser.add_argument('--transformer_heads', type=int, default=8)
724
+ return parser.parse_args()
725
+
726
+
727
+ def main():
728
+ args = parse_args()
729
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
730
+ print(f"Using device: {device}")
731
+
732
+ loader = FixedGAPartNetLoader(dataset_root=args.dataset_root)
733
+ if len(loader.object_list) == 0:
734
+ print("Error: empty dataset.")
735
+ return
736
+
737
+ ids_list = [os.path.basename(p) for p in loader.object_list]
738
+ if args.sample_id not in ids_list:
739
+ print(f"ERROR: Sample ID '{args.sample_id}' not found.")
740
+ return
741
+
742
+ idx = ids_list.index(args.sample_id)
743
+
744
+ model, actual_num_frames = load_model(args.checkpoint, device, args)
745
+ if model is None: return
746
+
747
+ num_frames_to_gen = args.num_frames if args.num_frames is not None else actual_num_frames
748
+
749
+ run_vae_diversity_test(
750
+ model, loader, idx, device, args.output_dir,
751
+ num_frames=num_frames_to_gen,
752
+ num_samples_to_gen=args.num_samples,
753
+ force_rotation=args.force_rotation,
754
+ fps=args.fps,
755
+ loop_mode=args.loop_mode
756
+ )
757
+
758
+
759
+ if __name__ == '__main__':
760
+ main()
761
+
762
+ def run_animation_from_sample(model, sample, sample_name, device, output_root, num_frames, num_samples_to_gen, force_rotation=False, include_groundtruth=False, fps: float = 5.0, loop_mode: str = "pingpong"):
763
+ """Run the inference_animation pipeline on a custom sample dict."""
764
+ initial_mesh = sample['initial_mesh']
765
+ vertex_part_mask = np.asarray(sample['part_mask'])
766
+ if vertex_part_mask.dtype != bool:
767
+ vertex_part_mask = vertex_part_mask.astype(bool)
768
+ bounds = initial_mesh.bounds
769
+ center = (bounds[0] + bounds[1]) / 2.0
770
+ scale = (bounds[1] - bounds[0]).max()
771
+ if scale < 1e-6:
772
+ scale = 1.0
773
+ initial_mesh_normalized = initial_mesh.copy()
774
+ initial_mesh_normalized.vertices = (initial_mesh_normalized.vertices - center) / scale
775
+ initial_pc, face_indices = trimesh.sample.sample_surface(initial_mesh_normalized, 4096)
776
+ sampled_part_mask_np = np.zeros(4096, dtype=np.float32)
777
+ for i, fid in enumerate(face_indices):
778
+ face_vertices = initial_mesh.faces[fid]
779
+ face_mask_values = vertex_part_mask[face_vertices]
780
+ sampled_part_mask_np[i] = np.bincount(face_mask_values.astype(int)).argmax()
781
+ part_mask_bool_idx_torch = torch.from_numpy(vertex_part_mask).bool().to(device)
782
+ drag_point = np.asarray(sample['drag_point'])
783
+ drag_vector = np.asarray(sample['drag_vector'])
784
+ drag_point_norm = (drag_point - center) / scale
785
+ drag_vector_norm = drag_vector / scale
786
+ joint_type_raw = sample['joint_type']
787
+ if isinstance(joint_type_raw, str):
788
+ joint_type_str = joint_type_raw
789
+ else:
790
+ joint_type_str = 'revolute' if joint_type_raw == 0 else 'prismatic'
791
+ joint_type = 0 if joint_type_str in ['revolute', 'continuous'] else 1
792
+ if force_rotation:
793
+ joint_type = 0
794
+ print('*** Forcing rotation mode (joint_type=0) ***')
795
+ joint_axis = np.asarray(sample['joint_axis'])
796
+ joint_origin = np.asarray(sample['joint_origin'])
797
+ joint_origin_norm = (joint_origin - center) / scale
798
+ rotation_direction_gt = sample.get('rotation_direction')
799
+ trajectory_vectors_gt = sample.get('trajectory_vectors')
800
+ drag_trajectory_gt = sample.get('drag_trajectory')
801
+ pc_tensor = torch.from_numpy(initial_pc).float().unsqueeze(0).to(device)
802
+ part_mask_tensor = torch.from_numpy(sampled_part_mask_np).float().unsqueeze(0).to(device)
803
+ drag_point_tensor = torch.from_numpy(drag_point_norm).float().unsqueeze(0).to(device)
804
+ drag_vector_tensor = torch.from_numpy(drag_vector_norm).float().unsqueeze(0).to(device)
805
+ joint_type_tensor = torch.tensor([joint_type], dtype=torch.long).to(device)
806
+ joint_axis_tensor = torch.from_numpy(joint_axis).float().unsqueeze(0).to(device)
807
+ joint_origin_tensor = torch.from_numpy(joint_origin_norm).float().unsqueeze(0).to(device)
808
+ rotation_direction_tensor = None if rotation_direction_gt is None else torch.from_numpy(rotation_direction_gt).float().unsqueeze(0).to(device)
809
+ trajectory_vectors_tensor = None if trajectory_vectors_gt is None else torch.from_numpy(trajectory_vectors_gt).float().unsqueeze(0).to(device)
810
+ drag_trajectory_tensor = None if drag_trajectory_gt is None else torch.from_numpy(drag_trajectory_gt).float().unsqueeze(0).to(device)
811
+ print('Running model ENCODER...')
812
+ with torch.no_grad():
813
+ combined_condition_feat, joint_feat = model.encode_features(
814
+ mesh=pc_tensor,
815
+ part_mask=part_mask_tensor,
816
+ drag_point=drag_point_tensor,
817
+ drag_vector=drag_vector_tensor,
818
+ joint_type=joint_type_tensor,
819
+ joint_axis=joint_axis_tensor,
820
+ joint_origin=joint_origin_tensor,
821
+ rotation_direction=rotation_direction_tensor,
822
+ trajectory_vectors=trajectory_vectors_tensor,
823
+ drag_trajectory=drag_trajectory_tensor
824
+ )
825
+ mu = model.fc_mu(combined_condition_feat)
826
+ logvar = model.fc_logvar(combined_condition_feat)
827
+ output_dir_id = os.path.join(output_root, sample_name)
828
+ os.makedirs(output_dir_id, exist_ok=True)
829
+ try:
830
+ initial_mesh.export(os.path.join(output_dir_id, 'initial_static.glb'))
831
+ except Exception:
832
+ pass
833
+ verts_normalized_torch = torch.from_numpy(initial_mesh_normalized.vertices).float().to(device)
834
+ faces_np = initial_mesh.faces
835
+ print(f"\nRunning model DECODER ({num_samples_to_gen} times)...")
836
+ for s_idx in range(num_samples_to_gen):
837
+ print(f"--- Sample {s_idx+1}/{num_samples_to_gen} ---")
838
+ with torch.no_grad():
839
+ if s_idx == 0 and num_samples_to_gen > 1:
840
+ z = mu
841
+ else:
842
+ z = model.reparameterize(mu, logvar)
843
+ pred_qr_seq, pred_qd_seq = model.decode(z, joint_feat, joint_axis_tensor, joint_type_tensor)
844
+ pred_qr_seq = pred_qr_seq.squeeze(0)
845
+ pred_qd_seq = pred_qd_seq.squeeze(0)
846
+ if joint_type == 0:
847
+ pred_qd_seq = torch.zeros_like(pred_qd_seq)
848
+ axis_expanded = joint_axis_tensor.expand(pred_qr_seq.shape[0], -1)
849
+ pred_qr_seq = project_rotation_to_axis(pred_qr_seq, axis_expanded)
850
+ else:
851
+ identity_qr = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device)
852
+ pred_qr_seq = identity_qr.unsqueeze(0).expand(pred_qr_seq.shape[0], -1)
853
+ pred_qr_conj = quaternion_conjugate(pred_qr_seq)
854
+ pred_t_q = 2.0 * quaternion_multiply(pred_qd_seq, pred_qr_conj)
855
+ pred_t_vec = pred_t_q[..., 1:]
856
+ axis_vec = joint_axis_tensor.squeeze(0)
857
+ dot_prod = torch.sum(pred_t_vec * axis_vec, dim=-1, keepdim=True)
858
+ t_parallel = dot_prod * axis_vec
859
+ pred_qd_seq = torch.cat([torch.zeros_like(pred_t_vec[..., 0:1]), t_parallel], dim=-1) * 0.5
860
+ # Generate a "single interaction" trajectory (avoid cumulative spinning).
861
+ if loop_mode not in ["once", "pingpong"]:
862
+ loop_mode = "pingpong"
863
+ t_values = _make_loop_t_values(num_frames, loop_mode=loop_mode, device=device)
864
+ if joint_type == 0:
865
+ qr_start = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=pred_qr_seq.dtype)
866
+ qr_final = pred_qr_seq[-1].clone()
867
+ pred_qr_seq = _nlerp_quaternion_sequence(qr_start, qr_final, t_values)
868
+ pred_qd_seq = torch.zeros((num_frames, 4), device=device, dtype=pred_qd_seq.dtype)
869
+ else:
870
+ qd_final = -pred_qd_seq[-1].clone()
871
+ qd_start = torch.tensor([0.0, 0.0, 0.0, 0.0], device=device, dtype=pred_qd_seq.dtype)
872
+ qr_start = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=pred_qr_seq.dtype)
873
+ pred_qr_seq = qr_start.unsqueeze(0).expand(num_frames, -1)
874
+ pred_qd_seq = (1.0 - t_values.unsqueeze(-1)) * qd_start.unsqueeze(0) + t_values.unsqueeze(-1) * qd_final.unsqueeze(0)
875
+ base_output_path = os.path.join(output_dir_id, f'predicted_z_{s_idx}')
876
+ pred_mesh_sequence = []
877
+ joint_origin_t = joint_origin_tensor.squeeze(0)
878
+ for i in range(num_frames):
879
+ qr = pred_qr_seq[i]
880
+ qd = pred_qd_seq[i]
881
+ deformed_verts = verts_normalized_torch.clone()
882
+ movable_verts = verts_normalized_torch[part_mask_bool_idx_torch]
883
+ movable_verts_shifted = movable_verts - joint_origin_t
884
+ transformed_movable = dual_quaternion_apply((qr, qd), movable_verts_shifted)
885
+ transformed_movable = transformed_movable + joint_origin_t
886
+ deformed_verts = deformed_verts.clone()
887
+ deformed_verts[part_mask_bool_idx_torch] = transformed_movable
888
+ denormalized_verts = deformed_verts.cpu().numpy() * scale + center
889
+ pred_mesh = trimesh.Trimesh(vertices=denormalized_verts, faces=faces_np, process=False)
890
+ pred_mesh.visual = initial_mesh.visual
891
+ pred_mesh_sequence.append(pred_mesh)
892
+ create_animation_video_local(pred_mesh_sequence, base_output_path + '.mp4', fps=fps)
893
+ create_gif(pred_mesh_sequence, base_output_path + '.gif', fps=fps)
894
+ if pygltflib is not None:
895
+ export_animated_glb(
896
+ initial_mesh=initial_mesh,
897
+ part_mask_np=vertex_part_mask,
898
+ qr_seq_tensor=pred_qr_seq,
899
+ qd_seq_tensor=pred_qd_seq,
900
+ joint_origin_norm_tensor=joint_origin_tensor.squeeze(0),
901
+ scale=scale,
902
+ center=center,
903
+ output_path=base_output_path + '.glb',
904
+ fps=fps
905
+ )
906
+ if include_groundtruth and 'qr_sequence' in sample and 'qd_sequence' in sample:
907
+ print("Processing GROUND TRUTH animation (using GT KPs for comparison)...")
908
+ gt_qr_seq = torch.from_numpy(sample['qr_sequence']).float().to(device)
909
+ gt_qd_seq = torch.from_numpy(sample['qd_sequence']).float().to(device)
910
+ gt_mesh_sequence = []
911
+ gt_origin_tensor = torch.from_numpy((sample['joint_origin'] - center) / scale).float().to(device)
912
+ for i in tqdm(range(num_frames), desc="Ground Truth"):
913
+ qr, qd = gt_qr_seq[i], gt_qd_seq[i]
914
+ deformed_verts = verts_normalized_torch.clone()
915
+ movable_verts = verts_normalized_torch[part_mask_bool_idx_torch]
916
+ joint_origin_t = gt_origin_tensor.squeeze(0)
917
+ movable_verts_shifted = movable_verts - joint_origin_t
918
+ transformed_movable = dual_quaternion_apply((qr, qd), movable_verts_shifted)
919
+ transformed_movable = transformed_movable + joint_origin_t
920
+ deformed_verts[part_mask_bool_idx_torch] = transformed_movable
921
+ denormalized_verts = deformed_verts.cpu().numpy() * scale + center
922
+ gt_mesh = trimesh.Trimesh(vertices=denormalized_verts, faces=faces_np, process=False)
923
+ gt_mesh.visual = initial_mesh.visual
924
+ gt_mesh_sequence.append(gt_mesh)
925
+ base_gt_output_path = os.path.join(output_dir_id, 'groundtruth_gt_kps')
926
+ create_animation_video_local(gt_mesh_sequence, base_gt_output_path + '.mp4', fps=fps)
927
+ create_gif(gt_mesh_sequence, base_gt_output_path + '.gif', fps=fps)
928
+ print(f"{'='*60} VAE Diversity Test complete! Output saved to: {output_dir_id}{'='*60}")
929
+ else:
930
+ print(f"{'='*60}VAE Animation complete! Output saved to: {output_dir_id}{'='*60}")
DragMesh/dragmesh/inference/inference_animation_kpp.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ inference_animation_kpp.py
3
+
4
+ This script mirrors the inference/export logic in `inference_animation.py` and optionally
5
+ overrides joint parameters using a Keypoint Predictor (KPP): joint_type / joint_axis / joint_origin.
6
+ """
7
+
8
+ import argparse
9
+ import os
10
+ import sys
11
+ from typing import Optional, Sequence, Tuple
12
+
13
+ import numpy as np
14
+ import torch
15
+ import trimesh
16
+
17
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
18
+
19
+ from dragmesh.data.data_loader_v2 import GAPartNetLoaderV2
20
+ from dragmesh.models.predictor import KeypointPredictor
21
+ from dragmesh.utils.kpp_normalization import (
22
+ KPP_ORIGIN_NORMALIZATION,
23
+ denormalize_points,
24
+ mesh_center_scale,
25
+ normalize_points,
26
+ normalize_vector,
27
+ )
28
+
29
+ # Reuse the canonical animation logic (single-interaction trajectory, loop_mode, headless rendering
30
+ # fallback, and animated GLB injection).
31
+ from dragmesh.inference.inference_animation import FixedGAPartNetLoader, load_model, run_animation_from_sample
32
+
33
+
34
+ def _parse_vec3(value: Optional[str]) -> Optional[np.ndarray]:
35
+ if value is None:
36
+ return None
37
+ parts = [p for p in value.replace(",", " ").split() if p]
38
+ if len(parts) != 3:
39
+ raise ValueError(f"Expected a 3D vector, got: {value!r}")
40
+ return np.asarray([float(p) for p in parts], dtype=np.float32)
41
+
42
+
43
+ def load_kpp_model(checkpoint_path: str, device: torch.device) -> Optional[KeypointPredictor]:
44
+ try:
45
+ checkpoint = torch.load(checkpoint_path, map_location='cpu')
46
+ except Exception as exc:
47
+ print(f"Error: unable to load KPP checkpoint: {exc}")
48
+ return None
49
+ config = checkpoint.get('config', {})
50
+ ckpt_norm = config.get('origin_normalization', config.get('kpp_origin_normalization'))
51
+ if ckpt_norm != KPP_ORIGIN_NORMALIZATION:
52
+ print(
53
+ "[WARN] KPP checkpoint origin_normalization="
54
+ f"{ckpt_norm!r}; expected {KPP_ORIGIN_NORMALIZATION!r}. "
55
+ "Old checkpoints trained with joint-origin-centered labels predict a near-zero origin "
56
+ "in the normalized frame and should be retrained after rebuilding LMDB."
57
+ )
58
+ kpp_model = KeypointPredictor(
59
+ use_mask=config.get('use_mask', True),
60
+ use_drag=config.get('use_drag', True)
61
+ ).to(device)
62
+ state = {k.replace('module.', ''): v for k, v in checkpoint.get('model_state_dict', {}).items()}
63
+ try:
64
+ kpp_model.load_state_dict(state, strict=True)
65
+ except RuntimeError as exc:
66
+ print(f"[WARN] KPP strict load failed, fallback to strict=False: {exc}")
67
+ kpp_model.load_state_dict(state, strict=False)
68
+ kpp_model.eval()
69
+ return kpp_model
70
+
71
+
72
+ def _prepare_kpp_inputs_from_mesh(initial_mesh: trimesh.Trimesh,
73
+ vertex_part_mask: np.ndarray,
74
+ drag_point_world: np.ndarray,
75
+ drag_vector_world: np.ndarray,
76
+ num_points: int = 4096) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, float]:
77
+ """
78
+ Match the KPP training normalization protocol:
79
+ - Normalize the mesh with bbox center/scale
80
+ - Sample a surface point cloud with `num_points`
81
+ - Derive per-sampled-point mask via face -> vertex majority vote (0/1)
82
+ - Normalize drag point/vector with the same center/scale
83
+ """
84
+ center, scale = mesh_center_scale(initial_mesh)
85
+
86
+ mesh_norm = initial_mesh.copy()
87
+ mesh_norm.vertices = normalize_points(mesh_norm.vertices, center, scale)
88
+
89
+ pc, face_indices = trimesh.sample.sample_surface(mesh_norm, num_points)
90
+
91
+ sampled_mask = np.zeros((len(face_indices),), dtype=np.float32)
92
+ # vertex_part_mask is per-vertex (bool/0/1). For each sampled point, use majority vote on its face.
93
+ for i, fid in enumerate(face_indices):
94
+ face_vertices = initial_mesh.faces[int(fid)]
95
+ face_mask_values = vertex_part_mask[face_vertices].astype(np.int32)
96
+ sampled_mask[i] = float(np.bincount(face_mask_values).argmax())
97
+
98
+ drag_point_norm = normalize_points(drag_point_world, center, scale)
99
+ drag_vector_norm = normalize_vector(drag_vector_world, scale)
100
+ return pc, sampled_mask, drag_point_norm, drag_vector_norm, center, scale
101
+
102
+
103
+ def run_kpp_animation(model,
104
+ loader: GAPartNetLoaderV2,
105
+ sample_idx: int,
106
+ device: torch.device,
107
+ output_dir: str,
108
+ num_frames: int,
109
+ num_samples_to_gen: int,
110
+ kpp_model: Optional[KeypointPredictor],
111
+ force_rotation: bool,
112
+ fps: float,
113
+ loop_mode: str,
114
+ use_kpp_type: bool = True,
115
+ drag_point_world: Optional[Sequence[float]] = None,
116
+ drag_vector_world: Optional[Sequence[float]] = None,
117
+ origin_prior_world: Optional[Sequence[float]] = None,
118
+ origin_from_drag_start: bool = False):
119
+ sample = loader.generate_training_sample(sample_idx, num_frames=num_frames)
120
+ if sample is None:
121
+ print(f"Error: unable to generate a valid sample for index={sample_idx}.")
122
+ return
123
+
124
+ initial_mesh = sample['initial_mesh']
125
+ vertex_part_mask = np.asarray(sample['part_mask'])
126
+ if vertex_part_mask.dtype != bool:
127
+ vertex_part_mask = vertex_part_mask.astype(bool)
128
+
129
+ drag_point = np.asarray(
130
+ sample['drag_point'] if drag_point_world is None else drag_point_world,
131
+ dtype=np.float32,
132
+ )
133
+ drag_vector = np.asarray(
134
+ sample['drag_vector'] if drag_vector_world is None else drag_vector_world,
135
+ dtype=np.float32,
136
+ )
137
+ if drag_point_world is not None or drag_vector_world is not None:
138
+ print(f"[Input] override_drag_point={drag_point.tolist()}, override_drag_vector={drag_vector.tolist()}")
139
+
140
+ # Default: use GT joint parameters (same behavior as inference_animation.py).
141
+ joint_type_str = sample['joint_type']
142
+ joint_axis = np.asarray(sample['joint_axis'], dtype=np.float32)
143
+ joint_origin = np.asarray(sample['joint_origin'], dtype=np.float32)
144
+ joint_type_int = 0 if joint_type_str in ['revolute', 'continuous'] else 1
145
+
146
+ # If KPP is provided: override joint parameters with predictions (the only difference vs animation).
147
+ if kpp_model is not None:
148
+ pc, sampled_mask, drag_point_norm, drag_vector_norm, center, scale = _prepare_kpp_inputs_from_mesh(
149
+ initial_mesh=initial_mesh,
150
+ vertex_part_mask=vertex_part_mask.astype(np.int32),
151
+ drag_point_world=drag_point,
152
+ drag_vector_world=drag_vector,
153
+ num_points=4096
154
+ )
155
+
156
+ with torch.no_grad():
157
+ pc_tensor = torch.from_numpy(pc).float().unsqueeze(0).to(device)
158
+ mask_tensor = torch.from_numpy(sampled_mask).float().unsqueeze(0).to(device)
159
+ drag_point_tensor = torch.from_numpy(drag_point_norm).float().unsqueeze(0).to(device)
160
+ drag_vector_tensor = torch.from_numpy(drag_vector_norm).float().unsqueeze(0).to(device)
161
+ pred_type_logits, pred_axis, pred_origin = kpp_model(
162
+ pc_tensor, mask_tensor, drag_point_tensor, drag_vector_tensor
163
+ )
164
+
165
+ pred_axis_np = pred_axis.squeeze(0).detach().cpu().numpy().astype(np.float32)
166
+ pred_axis_np = pred_axis_np / (np.linalg.norm(pred_axis_np) + 1e-8)
167
+ pred_origin_norm = pred_origin.squeeze(0).detach().cpu().numpy().astype(np.float32)
168
+ pred_origin_world = denormalize_points(pred_origin_norm, center, scale)
169
+
170
+ joint_axis = pred_axis_np
171
+ joint_origin = pred_origin_world
172
+ if use_kpp_type and pred_type_logits is not None:
173
+ joint_type_int = int(torch.argmax(pred_type_logits, dim=-1).item())
174
+ joint_type_str = 'revolute' if joint_type_int == 0 else 'prismatic'
175
+
176
+ if origin_prior_world is not None:
177
+ joint_origin = np.asarray(origin_prior_world, dtype=np.float32)
178
+ print("[KPP] origin_prior_world enabled; using explicit 3D anchor as joint origin prior.")
179
+ elif origin_from_drag_start:
180
+ joint_origin = drag_point.astype(np.float32)
181
+ print("[KPP] origin_from_drag_start enabled; using input drag point as joint origin prior.")
182
+
183
+ print(f"[KPP] origin_normalization={KPP_ORIGIN_NORMALIZATION}, center={center.tolist()}, scale={float(scale)}")
184
+ print(f"[KPP] joint_type={joint_type_str}, axis={joint_axis.tolist()}, origin={joint_origin.tolist()}")
185
+
186
+ if force_rotation:
187
+ joint_type_int = 0
188
+ joint_type_str = 'revolute'
189
+ print("*** Forcing rotation mode (joint_type=0) ***")
190
+
191
+ chosen_id = os.path.basename(loader.object_list[sample_idx])
192
+ output_dir_id = os.path.join(output_dir, chosen_id)
193
+ os.makedirs(output_dir_id, exist_ok=True)
194
+
195
+ # Build an "animation-compatible" sample dict and reuse run_animation_from_sample().
196
+ sample_for_anim = {
197
+ 'initial_mesh': initial_mesh,
198
+ 'part_mask': vertex_part_mask,
199
+ 'drag_point': drag_point,
200
+ 'drag_vector': drag_vector,
201
+ 'joint_type': joint_type_str,
202
+ 'joint_axis': joint_axis,
203
+ 'joint_origin': joint_origin,
204
+ # Optional conditioning fields (keep consistent with training if available).
205
+ 'rotation_direction': sample.get('rotation_direction'),
206
+ 'trajectory_vectors': sample.get('trajectory_vectors'),
207
+ 'drag_trajectory': sample.get('drag_trajectory'),
208
+ }
209
+
210
+ run_animation_from_sample(
211
+ model=model,
212
+ sample=sample_for_anim,
213
+ sample_name=chosen_id,
214
+ device=device,
215
+ output_root=output_dir,
216
+ num_frames=num_frames,
217
+ num_samples_to_gen=num_samples_to_gen,
218
+ force_rotation=False, # already handled above
219
+ include_groundtruth=False,
220
+ fps=fps,
221
+ loop_mode=loop_mode
222
+ )
223
+
224
+
225
+ def parse_args():
226
+ parser = argparse.ArgumentParser(description='VAE Animation Inference (optionally with KPP joint prediction)')
227
+ parser.add_argument('--dataset_root', type=str, required=True)
228
+ parser.add_argument('--checkpoint', type=str, required=True, help='VAE checkpoint')
229
+ parser.add_argument('--sample_id', type=str, required=True)
230
+ parser.add_argument('--output_dir', type=str, default='results_animation_kpp')
231
+ parser.add_argument('--num_samples', type=int, default=1)
232
+ parser.add_argument('--force_rotation', action='store_true')
233
+ parser.add_argument('--latent_dim', type=int, default=256)
234
+ parser.add_argument('--num_frames', type=int, default=None)
235
+ parser.add_argument('--transformer_layers', type=int, default=4)
236
+ parser.add_argument('--transformer_heads', type=int, default=8)
237
+
238
+ parser.add_argument('--kpp_checkpoint', type=str, default=None, help='Path to KPP weights (optional)')
239
+ parser.add_argument('--use_kpp_type', action='store_true', default=True, help='Use KPP predicted joint type (default: True)')
240
+ parser.add_argument('--no_use_kpp_type', action='store_false', dest='use_kpp_type',
241
+ help='Do not override joint type; only use KPP axis/origin.')
242
+ parser.add_argument('--drag_point_world', type=str, default=None,
243
+ help='Optional manifest/user 3D drag start as "x,y,z" in world coordinates.')
244
+ parser.add_argument('--drag_vector_world', type=str, default=None,
245
+ help='Optional manifest/user 3D drag vector as "x,y,z" in world coordinates.')
246
+ parser.add_argument('--origin_from_drag_start', action='store_true',
247
+ help='Use the input 3D drag start as an explicit joint-origin prior.')
248
+ parser.add_argument('--origin_prior_world', type=str, default=None,
249
+ help='Optional explicit 3D origin prior as "x,y,z"; does not alter KPP drag input.')
250
+
251
+ parser.add_argument('--fps', type=float, default=5.0, help='animation playback fps (smaller = slower)')
252
+ parser.add_argument('--loop_mode', type=str, default='pingpong', choices=['once', 'pingpong'],
253
+ help='once: 0->1; pingpong: 0->1->0 (better for default looping players)')
254
+ return parser.parse_args()
255
+
256
+
257
+ def main():
258
+ args = parse_args()
259
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
260
+ print(f"Using device: {device}")
261
+
262
+ loader = FixedGAPartNetLoader(dataset_root=args.dataset_root)
263
+ if len(loader.object_list) == 0:
264
+ print("Error: empty dataset.")
265
+ return
266
+
267
+ ids_list = [os.path.basename(p) for p in loader.object_list]
268
+ if args.sample_id not in ids_list:
269
+ print(f"ERROR: Sample ID '{args.sample_id}' not found.")
270
+ return
271
+
272
+ idx = ids_list.index(args.sample_id)
273
+
274
+ vae_model, actual_num_frames = load_model(args.checkpoint, device, args)
275
+ if vae_model is None:
276
+ return
277
+
278
+ num_frames_to_gen = args.num_frames if args.num_frames is not None else actual_num_frames
279
+
280
+ kpp_model = None
281
+ if args.kpp_checkpoint:
282
+ kpp_model = load_kpp_model(args.kpp_checkpoint, device=device)
283
+
284
+ run_kpp_animation(
285
+ model=vae_model,
286
+ loader=loader,
287
+ sample_idx=idx,
288
+ device=device,
289
+ output_dir=args.output_dir,
290
+ num_frames=num_frames_to_gen,
291
+ num_samples_to_gen=args.num_samples,
292
+ kpp_model=kpp_model,
293
+ force_rotation=args.force_rotation,
294
+ fps=args.fps,
295
+ loop_mode=args.loop_mode,
296
+ use_kpp_type=args.use_kpp_type,
297
+ drag_point_world=_parse_vec3(args.drag_point_world),
298
+ drag_vector_world=_parse_vec3(args.drag_vector_world),
299
+ origin_prior_world=_parse_vec3(args.origin_prior_world),
300
+ origin_from_drag_start=args.origin_from_drag_start
301
+ )
302
+
303
+
304
+ if __name__ == '__main__':
305
+ main()
DragMesh/dragmesh/models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (150 Bytes). View file
 
DragMesh/dragmesh/models/__pycache__/predictor.cpython-310.pyc ADDED
Binary file (5.31 kB). View file
 
DragMesh/dragmesh/utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (149 Bytes). View file
 
DragMesh/dragmesh/utils/__pycache__/kpp_normalization.cpython-310.pyc ADDED
Binary file (1.75 kB). View file
 
DragMesh/dragmesh/utils/logger.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Logging utilities for TensorBoard, Weights & Biases, and file logging.
3
+ """
4
+ import os
5
+ import logging
6
+ from datetime import datetime
7
+ from typing import Dict, Optional, Any
8
+
9
+
10
+ class Logger:
11
+ """Unified logger for TensorBoard, W&B, and file logging."""
12
+
13
+ def __init__(self, log_dir: str, use_tensorboard: bool = True, use_wandb: bool = False,
14
+ wandb_project: Optional[str] = None, wandb_config: Optional[Dict] = None,
15
+ use_file_logging: bool = True):
16
+ """
17
+ Initialize logger.
18
+
19
+ Args:
20
+ log_dir: Directory for logs
21
+ use_tensorboard: Whether to use TensorBoard
22
+ use_wandb: Whether to use Weights & Biases
23
+ wandb_project: W&B project name
24
+ wandb_config: W&B configuration dict
25
+ use_file_logging: Whether to log to file
26
+ """
27
+ self.use_tensorboard = use_tensorboard
28
+ self.use_wandb = use_wandb
29
+ self.use_file_logging = use_file_logging
30
+ self.log_dir = log_dir
31
+
32
+ # Initialize file logger
33
+ if self.use_file_logging:
34
+ self._init_file_logger()
35
+
36
+ # Initialize TensorBoard
37
+ if self.use_tensorboard:
38
+ try:
39
+ from torch.utils.tensorboard import SummaryWriter
40
+ self.tb_writer = SummaryWriter(log_dir=log_dir)
41
+ self.log_info(f"✓ TensorBoard logging to: {log_dir}")
42
+ except ImportError:
43
+ self.log_warning("⚠ TensorBoard not available. Install with: pip install tensorboard")
44
+ self.use_tensorboard = False
45
+ self.tb_writer = None
46
+ else:
47
+ self.tb_writer = None
48
+
49
+ # Initialize Weights & Biases
50
+ if self.use_wandb:
51
+ try:
52
+ import wandb
53
+ wandb.init(project=wandb_project, config=wandb_config, dir=log_dir)
54
+ self.log_info(f"✓ Weights & Biases logging to project: {wandb_project}")
55
+ except ImportError:
56
+ self.log_warning("⚠ W&B not available. Install with: pip install wandb")
57
+ self.use_wandb = False
58
+ except Exception as e:
59
+ self.log_warning(f"⚠ W&B initialization failed: {e}")
60
+ self.use_wandb = False
61
+
62
+ def _init_file_logger(self):
63
+ """Initialize file logger."""
64
+ os.makedirs(self.log_dir, exist_ok=True)
65
+
66
+ # Create log file with timestamp
67
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
68
+ log_file = os.path.join(self.log_dir, f'training_{timestamp}.log')
69
+
70
+ # Configure logger
71
+ self.file_logger = logging.getLogger('training_logger')
72
+ self.file_logger.setLevel(logging.INFO)
73
+
74
+ # Remove existing handlers to avoid duplicates
75
+ self.file_logger.handlers = []
76
+
77
+ # File handler
78
+ file_handler = logging.FileHandler(log_file)
79
+ file_handler.setLevel(logging.INFO)
80
+
81
+ # Console handler (optional, for debugging)
82
+ # console_handler = logging.StreamHandler()
83
+ # console_handler.setLevel(logging.INFO)
84
+
85
+ # Formatter
86
+ formatter = logging.Formatter(
87
+ '%(asctime)s - %(levelname)s - %(message)s',
88
+ datefmt='%Y-%m-%d %H:%M:%S'
89
+ )
90
+ file_handler.setFormatter(formatter)
91
+
92
+ self.file_logger.addHandler(file_handler)
93
+ # self.file_logger.addHandler(console_handler)
94
+
95
+ print(f"✓ File logging to: {log_file}")
96
+
97
+ def log_info(self, message: str):
98
+ """Log info message to file."""
99
+ if self.use_file_logging:
100
+ self.file_logger.info(message)
101
+
102
+ def log_warning(self, message: str):
103
+ """Log warning message to file."""
104
+ if self.use_file_logging:
105
+ self.file_logger.warning(message)
106
+ else:
107
+ print(message)
108
+
109
+ def log_error(self, message: str):
110
+ """Log error message to file."""
111
+ if self.use_file_logging:
112
+ self.file_logger.error(message)
113
+ else:
114
+ print(message)
115
+
116
+ def log_scalar(self, tag: str, value: float, step: int):
117
+ """Log a scalar value."""
118
+ if self.use_tensorboard and self.tb_writer is not None:
119
+ self.tb_writer.add_scalar(tag, value, step)
120
+
121
+ if self.use_wandb:
122
+ import wandb
123
+ wandb.log({tag: value}, step=step)
124
+
125
+ def log_scalars(self, main_tag: str, tag_scalar_dict: Dict[str, float], step: int):
126
+ """Log multiple scalar values."""
127
+ if self.use_tensorboard and self.tb_writer is not None:
128
+ self.tb_writer.add_scalars(main_tag, tag_scalar_dict, step)
129
+
130
+ if self.use_wandb:
131
+ import wandb
132
+ log_dict = {f"{main_tag}/{k}": v for k, v in tag_scalar_dict.items()}
133
+ wandb.log(log_dict, step=step)
134
+
135
+ def log_metrics(self, metrics: Dict[str, Any], step: int, prefix: str = ""):
136
+ """
137
+ Log multiple metrics at once.
138
+
139
+ Args:
140
+ metrics: Dictionary of metric names and values
141
+ step: Global step number
142
+ prefix: Prefix for metric names (e.g., 'train/', 'val/')
143
+ """
144
+ for key, value in metrics.items():
145
+ tag = f"{prefix}{key}" if prefix else key
146
+ self.log_scalar(tag, value, step)
147
+
148
+ def log_epoch_summary(self, epoch: int, train_metrics: Dict[str, float],
149
+ val_metrics: Dict[str, float], extra_info: Optional[Dict[str, Any]] = None):
150
+ """
151
+ Log epoch summary to file.
152
+
153
+ Args:
154
+ epoch: Epoch number
155
+ train_metrics: Training metrics
156
+ val_metrics: Validation metrics
157
+ extra_info: Additional info to log (e.g., lr, kl_weight)
158
+ """
159
+ if not self.use_file_logging:
160
+ return
161
+
162
+ summary_lines = [
163
+ "",
164
+ "="*80,
165
+ f"Epoch {epoch} Summary",
166
+ "="*80
167
+ ]
168
+
169
+ # Training metrics
170
+ summary_lines.append("\nTraining Metrics:")
171
+ for key, value in train_metrics.items():
172
+ if isinstance(value, float):
173
+ summary_lines.append(f" {key}: {value:.6f}")
174
+ else:
175
+ summary_lines.append(f" {key}: {value}")
176
+
177
+ # Validation metrics
178
+ summary_lines.append("\nValidation Metrics:")
179
+ for key, value in val_metrics.items():
180
+ if isinstance(value, float):
181
+ summary_lines.append(f" {key}: {value:.6f}")
182
+ else:
183
+ summary_lines.append(f" {key}: {value}")
184
+
185
+ # Extra info
186
+ if extra_info:
187
+ summary_lines.append("\nAdditional Info:")
188
+ for key, value in extra_info.items():
189
+ if isinstance(value, float):
190
+ summary_lines.append(f" {key}: {value:.6f}")
191
+ else:
192
+ summary_lines.append(f" {key}: {value}")
193
+
194
+ summary_lines.append("="*80)
195
+ summary_lines.append("")
196
+
197
+ # Log all lines
198
+ for line in summary_lines:
199
+ self.file_logger.info(line)
200
+
201
+ def close(self):
202
+ """Close all loggers."""
203
+ if self.use_tensorboard and self.tb_writer is not None:
204
+ self.tb_writer.close()
205
+
206
+ if self.use_wandb:
207
+ import wandb
208
+ wandb.finish()
209
+
210
+ if self.use_file_logging:
211
+ self.log_info("Training session ended.")
212
+ # Close file handlers
213
+ for handler in self.file_logger.handlers[:]:
214
+ handler.close()
215
+ self.file_logger.removeHandler(handler)
216
+
217
+
218
+ def create_logger(output_dir: str, use_tensorboard: bool = True, use_wandb: bool = False,
219
+ wandb_project: Optional[str] = None, wandb_config: Optional[Dict] = None,
220
+ use_file_logging: bool = True) -> Logger:
221
+ """
222
+ Create a logger instance.
223
+
224
+ Args:
225
+ output_dir: Output directory for logs
226
+ use_tensorboard: Whether to use TensorBoard
227
+ use_wandb: Whether to use W&B
228
+ wandb_project: W&B project name
229
+ wandb_config: W&B configuration dict
230
+ use_file_logging: Whether to log to file
231
+
232
+ Returns:
233
+ Logger instance
234
+ """
235
+ log_dir = os.path.join(output_dir, 'logs')
236
+ os.makedirs(log_dir, exist_ok=True)
237
+
238
+ return Logger(
239
+ log_dir=log_dir,
240
+ use_tensorboard=use_tensorboard,
241
+ use_wandb=use_wandb,
242
+ wandb_project=wandb_project,
243
+ wandb_config=wandb_config,
244
+ use_file_logging=use_file_logging
245
+ )
upstream/flash-linear-attention/tests/ops/test_delta.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+
5
+ import pytest
6
+ import torch
7
+ import torch.nn.functional as F
8
+
9
+ from fla.ops.delta_rule import chunk_delta_rule, fused_recurrent_delta_rule
10
+ from fla.utils import COMPILER_MODE, assert_close, device, device_platform
11
+
12
+ if COMPILER_MODE:
13
+ test_b_list = [1]
14
+ test_t_list = [4096]
15
+ test_t_varlen_list = test_t_list
16
+ test_d_list = [64, 128, 256]
17
+ else:
18
+ test_b_list = [2]
19
+ test_t_list = [15, 63, 300, 512]
20
+ test_t_varlen_list = [63, 286, 300, 512]
21
+ test_d_list = [64, 32, 100, 256]
22
+ test_h_list = [2]
23
+
24
+
25
+ @pytest.mark.parametrize('B', test_b_list)
26
+ @pytest.mark.parametrize('T', test_t_list)
27
+ @pytest.mark.parametrize('H', test_h_list)
28
+ @pytest.mark.parametrize('D', test_d_list)
29
+ @pytest.mark.parametrize('scale', [1])
30
+ @pytest.mark.parametrize('dtype', [torch.bfloat16])
31
+ @pytest.mark.skipif(
32
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
33
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
34
+ )
35
+ @pytest.mark.skipif(
36
+ device_platform == 'intel',
37
+ reason='Intel Triton Failure'
38
+ )
39
+ def test_chunk(
40
+ B: int,
41
+ T: int,
42
+ H: int,
43
+ D: int,
44
+ dtype: torch.dtype,
45
+ scale: float,
46
+ ):
47
+ torch.manual_seed(42)
48
+ q = torch.randn(B, T, H, D, dtype=dtype)
49
+ k = F.normalize(torch.randn(B, T, H, D, dtype=torch.float32), p=2, dim=-1).to(dtype)
50
+ v = torch.randn(B, T, H, D, dtype=dtype)
51
+ beta = torch.rand(B, T, H, dtype=dtype).sigmoid()
52
+ h0 = torch.randn(B, H, D, D, dtype=torch.float32)
53
+ q, k, v, beta, h0 = map(lambda x: x.to(device).requires_grad_(True), (q, k, v, beta, h0))
54
+ do = torch.rand_like(v)
55
+ dht = torch.rand_like(h0)
56
+
57
+ tri, tri_ht = chunk_delta_rule(
58
+ q.clone(),
59
+ k.clone(),
60
+ v.clone(),
61
+ beta.clone(),
62
+ scale=scale,
63
+ output_final_state=True,
64
+ initial_state=h0.clone(),
65
+ )
66
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward(retain_graph=True)
67
+ tri_dq, tri_dk, tri_dv, tri_dbeta, tri_dh0 = q.grad, k.grad, v.grad, beta.grad, h0.grad
68
+ q.grad = k.grad = v.grad = beta.grad = h0.grad = None
69
+
70
+ ref, ref_ht = fused_recurrent_delta_rule(
71
+ q.clone(),
72
+ k.clone(),
73
+ v.clone(),
74
+ beta.clone(),
75
+ scale=scale,
76
+ output_final_state=True,
77
+ initial_state=h0.clone(),
78
+ )
79
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward(retain_graph=True)
80
+ ref_dq, ref_dk, ref_dv, ref_dbeta, ref_dh0 = q.grad, k.grad, v.grad, beta.grad, h0.grad
81
+
82
+ assert_close(' o', ref, tri, 0.006)
83
+ assert_close(' ht', ref_ht, tri_ht, 0.006)
84
+ assert_close(' dq', ref_dq, tri_dq, 0.008)
85
+ assert_close(' dk', ref_dk, tri_dk, 0.008)
86
+ assert_close(' dv', ref_dv, tri_dv, 0.008)
87
+ assert_close(' db', ref_dbeta, tri_dbeta, 0.008)
88
+ assert_close('dh0', ref_dh0, tri_dh0, 0.008)
89
+
90
+
91
+ @pytest.mark.parametrize('N', [4])
92
+ @pytest.mark.parametrize('T', test_t_varlen_list)
93
+ @pytest.mark.parametrize('H', test_h_list)
94
+ @pytest.mark.parametrize('D', test_d_list)
95
+ @pytest.mark.parametrize('scale', [1])
96
+ @pytest.mark.parametrize('dtype', [torch.bfloat16])
97
+ @pytest.mark.skipif(
98
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '1',
99
+ reason='Skipping test_chunk_varlen because SKIP_TEST_CHUNK_VARLEN is set'
100
+ )
101
+ @pytest.mark.skipif(
102
+ device_platform == 'intel',
103
+ reason='Intel Triton Failure'
104
+ )
105
+ def test_chunk_varlen(
106
+ N: int,
107
+ T: int,
108
+ H: int,
109
+ D: int,
110
+ scale: float,
111
+ dtype: torch.dtype,
112
+ ):
113
+ torch.manual_seed(42)
114
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
115
+ # randomly split the sequence into N segments
116
+ cu_seqlens = torch.cat([
117
+ torch.tensor([0], dtype=torch.long),
118
+ torch.arange(16, T)[torch.randperm(T - 16)[:N-1]],
119
+ torch.tensor([T], dtype=torch.long)
120
+ ], 0).to(device).sort()[0]
121
+ # seq-first required for inputs with variable lengths
122
+ q = torch.randn((1, T, H, D), dtype=dtype)
123
+ k = F.normalize(torch.randn(1, T, H, D, dtype=torch.float32), p=2, dim=-1).to(dtype)
124
+ v = torch.randn((1, T, H, D), dtype=dtype)
125
+ beta = torch.rand(1, T, H, dtype=dtype).sigmoid()
126
+ h0 = torch.randn(N, H, D, D, dtype=dtype)
127
+ q, k, v, beta, h0 = map(lambda x: x.to(device).requires_grad_(), (q, k, v, beta, h0))
128
+ do = torch.randn_like(v)
129
+ dht = torch.rand_like(h0)
130
+
131
+ tri, tri_ht = chunk_delta_rule(
132
+ q.clone(),
133
+ k.clone(),
134
+ v.clone(),
135
+ beta.clone(),
136
+ scale=scale,
137
+ output_final_state=True,
138
+ initial_state=h0.clone(),
139
+ cu_seqlens=cu_seqlens,
140
+ )
141
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward(retain_graph=True)
142
+ tri_dq, tri_dk, tri_dv, tri_dbeta, tri_dh0 = q.grad, k.grad, v.grad, beta.grad, h0.grad
143
+ q.grad = k.grad = v.grad = beta.grad = h0.grad = None
144
+
145
+ ref, ref_ht = fused_recurrent_delta_rule(
146
+ q.clone(),
147
+ k.clone(),
148
+ v.clone(),
149
+ beta.clone(),
150
+ scale=scale,
151
+ output_final_state=True,
152
+ initial_state=h0.clone(),
153
+ cu_seqlens=cu_seqlens,
154
+ )
155
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward(retain_graph=True)
156
+ ref_dq, ref_dk, ref_dv, ref_dbeta, ref_dh0 = q.grad, k.grad, v.grad, beta.grad, h0.grad
157
+
158
+ assert_close(' o', ref, tri, 0.005)
159
+ assert_close(' ht', ref_ht, tri_ht, 0.005)
160
+ assert_close(' dq', ref_dq, tri_dq, 0.008)
161
+ assert_close(' dk', ref_dk, tri_dk, 0.008)
162
+ assert_close(' dv', ref_dv, tri_dv, 0.008)
163
+ assert_close(' db', ref_dbeta, tri_dbeta, 0.008)
164
+ assert_close('dh0', ref_dh0, tri_dh0, 0.008)
165
+
166
+
167
+ @pytest.mark.parametrize('B', test_b_list)
168
+ @pytest.mark.parametrize('T', test_t_list)
169
+ @pytest.mark.parametrize('H', test_h_list)
170
+ @pytest.mark.parametrize('D', test_d_list)
171
+ @pytest.mark.parametrize('scale', [0.1])
172
+ @pytest.mark.parametrize('dtype', [torch.float16])
173
+ @pytest.mark.skipif(
174
+ device_platform == 'intel',
175
+ reason='Intel Triton Failure'
176
+ )
177
+ def test_l2_in_kernel(
178
+ B: int,
179
+ T: int,
180
+ H: int,
181
+ D: int,
182
+ dtype: torch.dtype,
183
+ scale: float,
184
+ ):
185
+ q = torch.randn(B, T, H, D, dtype=dtype)
186
+ k = torch.randn(B, T, H, D, dtype=dtype)
187
+ v = torch.randn(B, T, H, D, dtype=dtype)
188
+ beta = torch.rand(B, T, H, dtype=dtype).sigmoid()
189
+ h0 = torch.randn(B, H, D, D, dtype=torch.float32)
190
+
191
+ q, k, v, beta, h0 = map(lambda x: x.to(device).requires_grad_(True), (q, k, v, beta, h0))
192
+ do = torch.rand_like(v)
193
+ dht = torch.rand_like(h0)
194
+
195
+ tri, tri_ht = chunk_delta_rule(
196
+ F.normalize(q.clone(), p=2, dim=-1).to(dtype),
197
+ F.normalize(k.clone(), p=2, dim=-1).to(dtype),
198
+ v.clone(),
199
+ beta.clone(),
200
+ scale=scale,
201
+ output_final_state=True,
202
+ initial_state=h0.clone(),
203
+ )
204
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward(retain_graph=True)
205
+ tri_dq, tri_dk, tri_dv, tri_dbeta, tri_dh0 = q.grad, k.grad, v.grad, beta.grad, h0.grad
206
+ q.grad = k.grad = v.grad = beta.grad = h0.grad = None
207
+
208
+ ref, ref_ht = chunk_delta_rule(
209
+ q.clone(),
210
+ k.clone(),
211
+ v.clone(),
212
+ beta.clone(),
213
+ scale=scale,
214
+ output_final_state=True,
215
+ initial_state=h0.clone(),
216
+ use_qk_l2norm_in_kernel=True
217
+ )
218
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward(retain_graph=True)
219
+ ref_dq, ref_dk, ref_dv, ref_dbeta, ref_dh0 = q.grad, k.grad, v.grad, beta.grad, h0.grad
220
+ q.grad = k.grad = v.grad = beta.grad = h0.grad = None
221
+ assert_close(' o', ref, tri, 0.01)
222
+ assert_close(' ht', ref_ht, tri_ht, 0.01)
223
+ assert_close(' dq', ref_dq, tri_dq, 0.01)
224
+ assert_close(' dk', ref_dk, tri_dk, 0.01)
225
+ assert_close(' dv', ref_dv, tri_dv, 0.01)
226
+ assert_close(' db', ref_dbeta, tri_dbeta, 0.01)
227
+ assert_close('dh0', ref_dh0, tri_dh0, 0.01)
228
+
229
+ tri, tri_ht = fused_recurrent_delta_rule(
230
+ F.normalize(q.clone().float(), p=2, dim=-1).to(dtype),
231
+ F.normalize(k.clone().float(), p=2, dim=-1).to(dtype),
232
+ v.clone(),
233
+ beta.clone(),
234
+ scale=scale,
235
+ output_final_state=True,
236
+ initial_state=h0.clone(),
237
+ )
238
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward(retain_graph=True)
239
+ tri_dq, tri_dk, tri_dv, tri_dbeta, tri_dh0 = q.grad, k.grad, v.grad, beta.grad, h0.grad
240
+ q.grad = k.grad = v.grad = beta.grad = h0.grad = None
241
+
242
+ ref, ref_ht = fused_recurrent_delta_rule(
243
+ q.clone(),
244
+ k.clone(),
245
+ v.clone(),
246
+ beta.clone(),
247
+ scale=scale,
248
+ output_final_state=True,
249
+ initial_state=h0.clone(),
250
+ use_qk_l2norm_in_kernel=True
251
+ )
252
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward(retain_graph=True)
253
+ ref_dq, ref_dk, ref_dv, ref_dbeta, ref_dh0 = q.grad, k.grad, v.grad, beta.grad, h0.grad
254
+ q.grad = k.grad = v.grad = beta.grad = h0.grad = None
255
+
256
+ assert_close(' o', ref, tri, 0.002)
257
+ assert_close(' ht', ref_ht, tri_ht, 0.002)
258
+ assert_close(' dq', ref_dq, tri_dq, 0.002)
259
+ assert_close(' dk', ref_dk, tri_dk, 0.002)
260
+ assert_close(' dv', ref_dv, tri_dv, 0.002)
261
+ assert_close(' db', ref_dbeta, tri_dbeta, 0.002)
262
+ assert_close('dh0', ref_dh0, tri_dh0, 0.002)
263
+
264
+ tri, tri_ht = fused_recurrent_delta_rule(
265
+ F.normalize(q.float().clone(), p=2, dim=-1).to(dtype),
266
+ F.normalize(k.float().clone(), p=2, dim=-1).to(dtype),
267
+ v.clone(),
268
+ beta.clone(),
269
+ scale=scale,
270
+ output_final_state=True,
271
+ initial_state=h0.clone(),
272
+ )
273
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward(retain_graph=True)
274
+ tri_dq, tri_dk, tri_dv, tri_dbeta, tri_dh0 = q.grad, k.grad, v.grad, beta.grad, h0.grad
275
+ q.grad = k.grad = v.grad = beta.grad = h0.grad = None
276
+
277
+ ref, ref_ht = fused_recurrent_delta_rule(
278
+ q.clone(),
279
+ k.clone(),
280
+ v.clone(),
281
+ beta.clone(),
282
+ scale=scale,
283
+ output_final_state=True,
284
+ initial_state=h0.clone(),
285
+ use_qk_l2norm_in_kernel=True
286
+ )
287
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward(retain_graph=True)
288
+ ref_dq, ref_dk, ref_dv, ref_dbeta, ref_dh0 = q.grad, k.grad, v.grad, beta.grad, h0.grad
289
+ q.grad = k.grad = v.grad = beta.grad = h0.grad = None
290
+ assert_close(' o', ref, tri, 0.002)
291
+ assert_close(' ht', ref_ht, tri_ht, 0.002)
292
+ assert_close(' dq', ref_dq, tri_dq, 0.002)
293
+ assert_close(' dk', ref_dk, tri_dk, 0.002)
294
+ assert_close(' dv', ref_dv, tri_dv, 0.002)
295
+ assert_close(' db', ref_dbeta, tri_dbeta, 0.002)
296
+ assert_close('dh0', ref_dh0, tri_dh0, 0.002)
upstream/flash-linear-attention/tests/ops/test_dplr_delta.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+
5
+ import pytest
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from einops import rearrange
9
+
10
+ from fla.ops.generalized_delta_rule.dplr import chunk_dplr_delta_rule, fused_recurrent_dplr_delta_rule
11
+ from fla.utils import COMPILER_MODE, assert_close, device, device_platform
12
+
13
+ if COMPILER_MODE:
14
+ test_b_list = [1]
15
+ test_t_list = [4096]
16
+ test_t_varlen_list = test_t_list
17
+ test_d_list = [64, 128, 256]
18
+ test_gate_list = [1.0]
19
+ else:
20
+ test_b_list = [2]
21
+ test_t_list = [1, 15, 63, 300]
22
+ test_t_varlen_list = [63, 286, 300, 512]
23
+ test_d_list = [32, 64, 100, 256]
24
+ test_gate_list = [1, 0.1, 10]
25
+ test_h_list = [2]
26
+
27
+
28
+ def recurrent_dplr_delta_rule_ref(
29
+ q: torch.Tensor,
30
+ k: torch.Tensor,
31
+ v: torch.Tensor,
32
+ a: torch.Tensor,
33
+ b: torch.Tensor,
34
+ gk: torch.Tensor,
35
+ scale: float = None,
36
+ initial_state: torch.Tensor = None,
37
+ output_final_state: bool = False,
38
+ ):
39
+ q, k, v, a, b, gk = map(lambda x: x.transpose(1, 2).to(torch.float), (q, k, v, a, b, gk))
40
+
41
+ B, H, T, K, V = *q.shape, v.shape[-1]
42
+ o = torch.zeros_like(v)
43
+ S = torch.zeros(B, H, K, V).to(v)
44
+ if initial_state is not None:
45
+ S = initial_state
46
+ if scale is None:
47
+ scale = K ** -0.5
48
+ q = q * scale
49
+
50
+ for i in range(T):
51
+ _q = q[:, :, i]
52
+ _k = k[:, :, i]
53
+ _v = v[:, :, i].clone()
54
+ a_i = a[:, :, i]
55
+ b_i = b[:, :, i]
56
+ # first matmul then decay in DPLR.
57
+ _v2 = (S.clone() * a_i[..., None]).sum(-2)
58
+ S = S.clone() * gk[:, :, i].exp()[..., None]
59
+ S = S.clone() + _k.unsqueeze(-1) * _v.unsqueeze(-2) + b_i.unsqueeze(-1) * _v2.unsqueeze(-2)
60
+ o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S)
61
+ if not output_final_state:
62
+ S = None
63
+ o = o.transpose(1, 2)
64
+ return o, S
65
+
66
+
67
+ def chunk_dplr_delta_rule_ref(
68
+ q: torch.Tensor,
69
+ k: torch.Tensor,
70
+ v: torch.Tensor,
71
+ a: torch.Tensor,
72
+ b: torch.Tensor,
73
+ gk: torch.Tensor,
74
+ initial_state: torch.Tensor = None,
75
+ output_final_state: bool = True,
76
+ scale: float = None,
77
+ chunk_size: int = 64,
78
+ ):
79
+ q, k, v, a, b, gk = map(lambda x: x.transpose(1, 2).to(torch.float), (q, k, v, a, b, gk))
80
+ BT = chunk_size
81
+ T = q.shape[-2]
82
+ pad_len = (BT - (T % BT)) % BT
83
+
84
+ q, k, v, a, b, gk = map(lambda x: F.pad(x, (0, 0, 0, pad_len)).to(torch.float), [q, k, v, a, b, gk])
85
+ B, H, _, K, V = *q.shape, v.shape[-1]
86
+ NT = q.shape[-2] // BT
87
+ if scale is None:
88
+ scale = K ** -0.5
89
+ q = q * scale
90
+
91
+ S = k.new_zeros(B, H, K, V)
92
+ if initial_state is not None:
93
+ S += initial_state
94
+
95
+ # note that diagonal is masked.
96
+ mask = torch.triu(torch.ones(BT, BT, dtype=torch.bool, device=q.device), diagonal=0)
97
+ q, k, v, a, b, gk = map(lambda x: rearrange(x, 'b h (n c) d -> b h n c d', c=BT), [q, k, v, a, b, gk])
98
+ gk_cumsum = gk.cumsum(-2)
99
+ A_ab = torch.zeros(B, H, NT, BT, BT).to(q.device)
100
+ A_qk = torch.zeros(B, H, NT, BT, BT).to(q.device)
101
+ A_ak = torch.zeros(B, H, NT, BT, BT).to(q.device)
102
+ A_qb = torch.zeros(B, H, NT, BT, BT).to(q.device)
103
+
104
+ for i in range(BT):
105
+ a_i = a[:, :, :, i, None]
106
+ q_i = q[:, :, :, i, None]
107
+ gk_i = gk_cumsum[:, :, :, i, None]
108
+ mask = (torch.arange(BT) <= i).to(q.device)
109
+ attn_i = (gk_i - gk_cumsum).masked_fill(~mask.unsqueeze(-1), float('-inf')).exp()
110
+ A_qk[:, :, :, i, :] = (q_i * k * attn_i).sum(-1).clone()
111
+ A_qb[:, :, :, i, :] = (q_i * b * attn_i).sum(-1).clone()
112
+ mask = (torch.arange(BT) < i).to(q.device)
113
+ # shift by one.
114
+ attn_i = (gk_i - gk[:, :, :, i, None] - gk_cumsum).masked_fill(~mask.unsqueeze(-1), float('-inf')).exp()
115
+ A_ab[:, :, :, i, :] = (a_i * b * attn_i).sum(-1).clone()
116
+ A_ak[:, :, :, i, :] = (a_i * k * attn_i).sum(-1).clone()
117
+
118
+ A_ab = A_ab
119
+ for i in range(1, BT):
120
+ A_ab[..., i, :i] = A_ab[..., i, :i].clone() + (A_ab[..., i, :, None].clone() * A_ab[..., :, :i].clone()).sum(-2)
121
+
122
+ A_ab = A_ab + torch.eye(BT, dtype=torch.float, device=q.device)
123
+ u = A_ab @ (A_ak @ v)
124
+ w = A_ab @ ((gk_cumsum-gk).exp() * a)
125
+
126
+ o = torch.zeros_like(v)
127
+ mask = torch.triu(torch.ones(BT, BT, dtype=torch.bool, device=q.device), diagonal=1)
128
+ for i in range(0, NT):
129
+ q_i, k_i, v_i, u_i, w_i, b_i = q[:, :, i], k[:, :, i], v[:, :, i], u[:, :, i], w[:, :, i], b[:, :, i]
130
+ v2_i = u_i + w_i @ S
131
+ o_1 = A_qk[:, :, i] @ v_i
132
+ o_2 = A_qb[:, :, i] @ v2_i
133
+ o_3 = (q_i * gk_cumsum[:, :, i].exp()) @ S
134
+ o[:, :, i] = o_1 + o_2 + o_3
135
+ decay = (gk_cumsum[:, :, i, -1, None] - gk_cumsum[:, :, i]).exp()
136
+ S = S*gk_cumsum[:, :, i, -1, :, None].exp() + (k_i * decay).transpose(-1, -2) @ v_i + \
137
+ (b_i * decay).transpose(-1, -2) @ v2_i
138
+
139
+ S = None if output_final_state is False else S
140
+ o = rearrange(o, 'b h n c d -> b h (n c) d')
141
+ o = o[:, :, :T].transpose(1, 2)
142
+ return o, S
143
+
144
+
145
+ @pytest.mark.parametrize('B', test_b_list)
146
+ @pytest.mark.parametrize('T', test_t_list)
147
+ @pytest.mark.parametrize('H', test_h_list)
148
+ @pytest.mark.parametrize('D', test_d_list)
149
+ @pytest.mark.parametrize('scale', [0.25])
150
+ @pytest.mark.parametrize('dtype', [torch.float16])
151
+ @pytest.mark.skipif(
152
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
153
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
154
+ )
155
+ def test_recurrent_fwd(
156
+ B: int,
157
+ T: int,
158
+ H: int,
159
+ D: int,
160
+ scale: float,
161
+ dtype: torch.dtype,
162
+ ):
163
+ torch.manual_seed(42)
164
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
165
+ os.environ['TORCH_CUDA_MATMUL_PRECISION'] = 'highest'
166
+ q = torch.randn(B, T, H, D, dtype=dtype)
167
+ k = torch.randn(B, T, H, D, dtype=dtype)
168
+ v = torch.randn(B, T, H, D, dtype=dtype)
169
+ a = torch.rand(B, T, H, D, dtype=dtype)
170
+ gk = torch.randn(B, T, H, D, dtype=torch.float)
171
+
172
+ a = F.normalize(a, p=2, dim=-1)
173
+ b = -a
174
+ gk = F.logsigmoid(gk) / 16
175
+
176
+ h0 = torch.randn(B, H, D, D, dtype=torch.float)
177
+ q, k, v, a, b, gk, h0 = map(lambda x: x.to(device).requires_grad_(False), (q, k, v, a, b, gk, h0))
178
+ ref, ref_ht = chunk_dplr_delta_rule_ref(
179
+ q=q.clone(),
180
+ k=k.clone(),
181
+ v=v.clone(),
182
+ a=a.clone(),
183
+ b=b.clone(),
184
+ gk=gk.clone(),
185
+ scale=scale,
186
+ initial_state=h0.clone(),
187
+ output_final_state=True,
188
+ )
189
+ tri, tri_ht = recurrent_dplr_delta_rule_ref(
190
+ q=q.clone(),
191
+ k=k.clone(),
192
+ v=v.clone(),
193
+ a=a.clone(),
194
+ b=b.clone(),
195
+ gk=gk.clone(),
196
+ scale=scale,
197
+ initial_state=h0.clone(),
198
+ output_final_state=True,
199
+ )
200
+ assert_close(' o', ref, tri, 0.001)
201
+ assert_close('ht', ref_ht, tri_ht, 0.001)
202
+
203
+
204
+ @pytest.mark.parametrize('B', test_b_list)
205
+ @pytest.mark.parametrize('T', test_t_list)
206
+ @pytest.mark.parametrize('H', test_h_list)
207
+ @pytest.mark.parametrize('D', test_d_list)
208
+ @pytest.mark.parametrize('scale', [0.25])
209
+ @pytest.mark.parametrize('dtype', [torch.float16])
210
+ @pytest.mark.skipif(
211
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
212
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
213
+ )
214
+ def test_fused_recurrent_fwd(
215
+ B: int,
216
+ T: int,
217
+ H: int,
218
+ D: int,
219
+ scale: float,
220
+ dtype: torch.dtype,
221
+ ):
222
+ torch.manual_seed(42)
223
+ q = torch.randn(B, T, H, D, dtype=dtype)
224
+ k = torch.randn(B, T, H, D, dtype=dtype)
225
+ v = torch.randn(B, T, H, D, dtype=dtype)
226
+ a = torch.rand(B, T, H, D, dtype=dtype)
227
+ gk = torch.randn(B, T, H, D, dtype=torch.float)
228
+
229
+ a = F.normalize(a, p=2, dim=-1)
230
+ b = -a
231
+ gk = F.logsigmoid(gk) / 4
232
+
233
+ h0 = torch.randn(B, H, D, D, dtype=torch.float)
234
+ q, k, v, a, b, gk, h0 = map(lambda x: x.to(device).requires_grad_(False), (q, k, v, a, b, gk, h0))
235
+ ref, ref_ht = recurrent_dplr_delta_rule_ref(
236
+ q=q.clone(),
237
+ k=k.clone(),
238
+ v=v.clone(),
239
+ a=a.clone(),
240
+ b=b.clone(),
241
+ gk=gk.clone(),
242
+ scale=scale,
243
+ initial_state=h0.clone(),
244
+ output_final_state=True,
245
+ )
246
+
247
+ tri, tri_ht = fused_recurrent_dplr_delta_rule(
248
+ q=q.clone(),
249
+ k=k.clone(),
250
+ v=v.clone(),
251
+ a=a.clone(),
252
+ b=b.clone(),
253
+ gk=gk.clone(),
254
+ scale=scale,
255
+ initial_state=h0.clone(),
256
+ output_final_state=True,
257
+ )
258
+ assert_close(' o', ref, tri, 0.002)
259
+ assert_close('ht', ref_ht, tri_ht, 0.002)
260
+
261
+
262
+ @pytest.mark.parametrize('B', test_b_list)
263
+ @pytest.mark.parametrize('T', test_t_list)
264
+ @pytest.mark.parametrize('H', test_h_list)
265
+ @pytest.mark.parametrize('D', test_d_list)
266
+ @pytest.mark.parametrize('gate_logit_normalizer', test_gate_list)
267
+ @pytest.mark.parametrize('scale', [0.25])
268
+ @pytest.mark.parametrize('dtype', [torch.float16])
269
+ @pytest.mark.parametrize('compile', [False, True])
270
+ @pytest.mark.skipif(
271
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
272
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
273
+ )
274
+ @pytest.mark.skipif(
275
+ device_platform == 'intel',
276
+ reason='Intel Triton Failure'
277
+ )
278
+ def test_chunk(
279
+ B: int,
280
+ T: int,
281
+ H: int,
282
+ D: int,
283
+ scale: float,
284
+ gate_logit_normalizer: float,
285
+ dtype: torch.dtype,
286
+ compile: bool,
287
+ ):
288
+ torch.manual_seed(42)
289
+ q = torch.randn(B, T, H, D, dtype=dtype)
290
+ k = torch.randn(B, T, H, D, dtype=dtype)
291
+ v = torch.randn(B, T, H, D, dtype=dtype)
292
+ a = torch.rand(B, T, H, D, dtype=dtype)
293
+ gk = torch.randn(B, T, H, D, dtype=torch.float)
294
+
295
+ a = F.normalize(a, p=2, dim=-1)
296
+ b = -a
297
+ gk = F.logsigmoid(gk) / gate_logit_normalizer
298
+
299
+ h0 = torch.randn(B, H, D, D, dtype=torch.float)
300
+ q, k, v, a, b, gk, h0 = map(lambda x: x.to(device).requires_grad_(True), (q, k, v, a, b, gk, h0))
301
+ ref, ref_ht = chunk_dplr_delta_rule_ref(
302
+ q=q.clone(),
303
+ k=k.clone(),
304
+ v=v.clone(),
305
+ a=a.clone(),
306
+ b=b.clone(),
307
+ gk=gk.clone(),
308
+ scale=scale,
309
+ initial_state=h0.clone(),
310
+ output_final_state=True,
311
+ )
312
+ do = torch.randn_like(v)
313
+ dht = torch.randn_like(h0)
314
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward(retain_graph=True)
315
+ ref_dq, ref_dk, ref_dv, ref_da, ref_db, ref_dg, ref_dh0 = q.grad, k.grad, v.grad, a.grad, b.grad, gk.grad, h0.grad
316
+ q.grad = k.grad = v.grad = a.grad = b.grad = gk.grad = h0.grad = None
317
+
318
+ chunk_compiled = torch.compile(chunk_dplr_delta_rule) if compile else chunk_dplr_delta_rule
319
+
320
+ tri, tri_ht = chunk_compiled(
321
+ q=q.clone(),
322
+ k=k.clone(),
323
+ v=v.clone(),
324
+ a=a.clone(),
325
+ b=b.clone(),
326
+ gk=gk.clone(),
327
+ scale=scale,
328
+ initial_state=h0.clone(),
329
+ output_final_state=True,
330
+ )
331
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward(retain_graph=True)
332
+ tri_dq, tri_dk, tri_dv, tri_da, tri_db, tri_dg, tri_dh0 = q.grad, k.grad, v.grad, a.grad, b.grad, gk.grad, h0.grad
333
+ q.grad = k.grad = v.grad = a.grad = b.grad = gk.grad = h0.grad = None
334
+
335
+ assert_close(' o', ref, tri, 0.007)
336
+ assert_close(' ht', ref_ht, tri_ht, 0.008)
337
+ assert_close(' dq', ref_dq, tri_dq, 0.008)
338
+ assert_close(' dk', ref_dk, tri_dk, 0.008)
339
+ assert_close(' dv', ref_dv, tri_dv, 0.008)
340
+ assert_close(' da', ref_da, tri_da, 0.008)
341
+ assert_close(' db', ref_db, tri_db, 0.008)
342
+ if gate_logit_normalizer >= 1 and ref_dg.norm() > 0.01: # otherwise it is meaningless
343
+ assert_close(' dg', ref_dg, tri_dg, 0.008)
344
+ assert_close('dh0', ref_dh0, tri_dh0, 0.008)
345
+
346
+
347
+ @pytest.mark.parametrize('N', test_b_list)
348
+ @pytest.mark.parametrize('T', test_t_varlen_list)
349
+ @pytest.mark.parametrize('H', test_h_list)
350
+ @pytest.mark.parametrize('D', test_d_list)
351
+ @pytest.mark.parametrize('scale', [0.25])
352
+ @pytest.mark.parametrize('dtype', [torch.float16])
353
+ @pytest.mark.skipif(
354
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '1',
355
+ reason='Skipping test_chunk_varlen because SKIP_TEST_CHUNK_VARLEN is set'
356
+ )
357
+ @pytest.mark.skipif(
358
+ device_platform == 'intel',
359
+ reason='Intel Triton Failure'
360
+ )
361
+ def test_chunk_varlen(
362
+ N: int,
363
+ T: int,
364
+ H: int,
365
+ D: int,
366
+ scale: float,
367
+ dtype: torch.dtype,
368
+ ):
369
+ torch.manual_seed(42)
370
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
371
+ # randomly split the sequence into N segments
372
+ cu_seqlens = torch.cat([
373
+ torch.tensor([0], dtype=torch.long),
374
+ torch.arange(16, T)[torch.randperm(T - 16)[:N-1]],
375
+ torch.tensor([T], dtype=torch.long)
376
+ ], 0).to(device).sort()[0]
377
+ # seq-first required for inputs with variable lengths
378
+ q = torch.randn(1, T, H, D, dtype=dtype)
379
+ k = torch.randn(1, T, H, D, dtype=dtype)
380
+ v = torch.randn(1, T, H, D, dtype=dtype)
381
+ a = torch.rand(1, T, H, D, dtype=dtype)
382
+ gk = torch.randn(1, T, H, D, dtype=torch.float)
383
+ a = F.normalize(a, p=2, dim=-1)
384
+ b = -a
385
+ gk = F.logsigmoid(gk)
386
+ h0 = torch.randn(N, H, D, D, dtype=torch.float)
387
+ q, k, v, a, b, gk, h0 = map(lambda x: x.to(device).requires_grad_(True), (q, k, v, a, b, gk, h0))
388
+
389
+ tri, tri_ht = chunk_dplr_delta_rule(
390
+ q=q.clone(),
391
+ k=k.clone(),
392
+ v=v.clone(),
393
+ a=a.clone(),
394
+ b=b.clone(),
395
+ gk=gk.clone(),
396
+ scale=scale,
397
+ output_final_state=True,
398
+ initial_state=h0.clone(),
399
+ cu_seqlens=cu_seqlens,
400
+ )
401
+ do = torch.randn_like(v)
402
+ dht = torch.randn_like(h0)
403
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward(retain_graph=True)
404
+ tri_dq, tri_dk, tri_dv, tri_da, tri_db, tri_dg, tri_dh0 = q.grad, k.grad, v.grad, a.grad, b.grad, gk.grad, h0.grad
405
+ q.grad = k.grad = v.grad = a.grad = b.grad = gk.grad = h0.grad = None
406
+
407
+ ref = []
408
+ ref_ht = []
409
+ for i in range(N):
410
+ ref_i, ref_ht_i = chunk_dplr_delta_rule_ref(
411
+ q=q[:, cu_seqlens[i]:cu_seqlens[i+1]],
412
+ k=k[:, cu_seqlens[i]:cu_seqlens[i+1]],
413
+ v=v[:, cu_seqlens[i]:cu_seqlens[i+1]],
414
+ a=a[:, cu_seqlens[i]:cu_seqlens[i+1]],
415
+ b=b[:, cu_seqlens[i]:cu_seqlens[i+1]],
416
+ gk=gk[:, cu_seqlens[i]:cu_seqlens[i+1]],
417
+ scale=scale,
418
+ initial_state=h0[i, None],
419
+ output_final_state=True,
420
+ )
421
+ ref.append(ref_i)
422
+ ref_ht.append(ref_ht_i)
423
+
424
+ ref = torch.cat(ref, 1)
425
+ ref_ht = torch.cat(ref_ht, 0)
426
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward(retain_graph=True)
427
+ ref_dq, ref_dk, ref_dv, ref_da, ref_db, ref_dg, ref_dh0 = q.grad, k.grad, v.grad, a.grad, b.grad, gk.grad, h0.grad
428
+
429
+ assert_close(' o', ref, tri, 0.007)
430
+ assert_close(' ht', ref_ht, tri_ht, 0.008)
431
+ assert_close(' dq', ref_dq, tri_dq, 0.008)
432
+ assert_close(' dk', ref_dk, tri_dk, 0.008)
433
+ assert_close(' dv', ref_dv, tri_dv, 0.008)
434
+ assert_close(' da', ref_da, tri_da, 0.008)
435
+ assert_close(' db', ref_db, tri_db, 0.008)
436
+ assert_close(' dg', ref_dg, tri_dg, 0.008)
437
+ assert_close('dh0', ref_dh0, tri_dh0, 0.008)
upstream/flash-linear-attention/tests/ops/test_gated_delta.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+
5
+ import pytest
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from einops import rearrange
9
+
10
+ from fla.ops.gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
11
+ from fla.utils import COMPILER_MODE, assert_close, device, is_intel_alchemist
12
+
13
+ if COMPILER_MODE:
14
+ test_b_list = [1]
15
+ test_t_list = [4096]
16
+ test_t_varlen_list = test_t_list
17
+ test_d_list = [64, 128, 256]
18
+ test_gate_list = [1.0]
19
+ else:
20
+ test_b_list = [2]
21
+ test_t_list = [1, 15, 63, 300]
22
+ test_t_varlen_list = [63, 286, 300, 512]
23
+ test_d_list = [64, 32, 100, 256]
24
+ test_gate_list = [1, 0.1, 10]
25
+ test_h_list = [2]
26
+
27
+
28
+ def recurrent_gated_delta_rule_ref(
29
+ q: torch.Tensor,
30
+ k: torch.Tensor,
31
+ v: torch.Tensor,
32
+ beta: torch.Tensor,
33
+ g: torch.Tensor,
34
+ scale: float = None,
35
+ initial_state: torch.Tensor = None,
36
+ output_final_state: bool = False,
37
+ ):
38
+ q, k, v, beta, g = map(lambda x: x.transpose(1, 2).contiguous().to(torch.float32), [q, k, v, beta, g])
39
+ B, H, T, K, V = *k.shape, v.shape[-1]
40
+ o = torch.zeros(B, H, T, V).to(v)
41
+ h = torch.zeros(B, H, K, V).to(v)
42
+ if initial_state is not None:
43
+ h = initial_state
44
+ if scale is None:
45
+ scale = 1 / (q.shape[-1] ** 0.5)
46
+ q = q * scale
47
+ for i in range(T):
48
+ b_q = q[:, :, i]
49
+ b_k = k[:, :, i]
50
+ b_v = v[:, :, i].clone()
51
+ h = h.clone() * g[:, :, i].exp()[..., None, None]
52
+ b_beta = beta[:, :, i]
53
+ b_v = b_v - (h.clone() * b_k[..., None]).sum(-2)
54
+ b_v = b_v * b_beta[..., None]
55
+ h = h.clone() + b_k.unsqueeze(-1) * b_v.unsqueeze(-2)
56
+ o[:, :, i] = torch.einsum('bhd,bhdm->bhm', b_q, h)
57
+ if not output_final_state:
58
+ h = None
59
+ o = o.transpose(1, 2).contiguous()
60
+ return o, h
61
+
62
+
63
+ def chunk_gated_delta_rule_ref(
64
+ q: torch.Tensor,
65
+ k: torch.Tensor,
66
+ v: torch.Tensor,
67
+ g: torch.Tensor,
68
+ beta: torch.Tensor,
69
+ chunk_size: int = 64,
70
+ scale: float = None,
71
+ initial_state: torch.Tensor = None,
72
+ output_final_state: bool = False,
73
+ ):
74
+ BT = chunk_size
75
+ if scale is None:
76
+ scale = 1 / (q.shape[-1] ** 0.5)
77
+ # Calculate padding needed to make T a multiple of BT
78
+ q, k, v, beta, g = map(lambda x: x.transpose(1, 2).contiguous().to(torch.float32), [q, k, v, beta, g])
79
+
80
+ T = q.shape[-2]
81
+ pad_len = (BT - (T % BT)) % BT
82
+ if pad_len > 0:
83
+ # Pad all tensors
84
+ q = F.pad(q, (0, 0, 0, pad_len))
85
+ k = F.pad(k, (0, 0, 0, pad_len))
86
+ v = F.pad(v, (0, 0, 0, pad_len))
87
+ beta = F.pad(beta, (0, pad_len))
88
+ g = F.pad(g, (0, pad_len))
89
+ q, k, v, beta, g = map(lambda x: x.to(torch.float32), [q, k, v, beta, g])
90
+ decay = g
91
+ chunk_size = BT
92
+ b, h, l, d_k = q.shape
93
+ d_v = v.shape[-1]
94
+ q = q * scale
95
+ v = v * beta[..., None]
96
+ k_beta = k * beta[..., None]
97
+ assert l % chunk_size == 0
98
+ # note that diagonal is masked.
99
+ mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=q.device), diagonal=0)
100
+ q, k, v, k_beta, decay = map(
101
+ lambda x: rearrange(x, 'b h (n c) d -> b h n c d', c=chunk_size),
102
+ [q, k, v, k_beta, decay.unsqueeze(-1)]
103
+ )
104
+ decay = decay.squeeze(-1).cumsum(-1)
105
+ L_mask = ((decay.unsqueeze(-1) - decay.unsqueeze(-2)).tril().exp().float()).tril()
106
+ attn = -((k_beta @ k.transpose(-1, -2)) * L_mask).masked_fill(mask, 0)
107
+ for i in range(1, chunk_size):
108
+ attn[..., i, :i] = attn[..., i, :i].clone() + (attn[..., i, :i, None].clone() * attn[..., :i, :i].clone()).sum(-2)
109
+ attn = attn + torch.eye(chunk_size, dtype=torch.float, device=q.device)
110
+ attn = attn
111
+ k_cumsum = attn @ v
112
+
113
+ attn = -((k_beta @ k.transpose(-1, -2))).masked_fill(mask, 0)
114
+ for i in range(1, chunk_size):
115
+ attn[..., i, :i] = attn[..., i, :i].clone() + (attn[..., i, :i, None].clone() * attn[..., :i, :i].clone()).sum(-2)
116
+ attn = attn + torch.eye(chunk_size, dtype=torch.float, device=q.device)
117
+ attn = attn
118
+ k_cumdecay = attn @ k_beta
119
+ v = k_cumsum
120
+ S = k.new_zeros(b, h, d_k, d_v)
121
+ if initial_state is not None:
122
+ S = initial_state
123
+ o = torch.zeros_like(v)
124
+ mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=q.device), diagonal=1)
125
+ for i in range(0, l // chunk_size):
126
+ q_i, k_i, v_i = q[:, :, i], k[:, :, i], v[:, :, i]
127
+ attn = (q_i @ k_i.transpose(-1, -2) * L_mask[:, :, i]).masked_fill_(mask, 0)
128
+ v_prime = (k_cumdecay[:, :, i] * decay[:, :, i, :, None].exp()) @ S
129
+ v_new = v_i - v_prime
130
+ o_inter = (q_i * decay[:, :, i, :, None].exp()) @ S
131
+ o[:, :, i] = o_inter + attn @ v_new
132
+ S = S * decay[:, :, i, -1, None, None].exp() + (k_i * (decay[:, :, i, -1, None] - decay[:, :, i]).exp()
133
+ [..., None]).transpose(-1, -2) @ v_new
134
+ if not output_final_state:
135
+ S = None
136
+ # unpad
137
+ o = rearrange(o, 'b h n c d -> b h (n c) d')
138
+ o = o[:, :, :T]
139
+ o = o.transpose(1, 2)
140
+ return o, S
141
+
142
+
143
+ @pytest.mark.parametrize('B', test_b_list)
144
+ @pytest.mark.parametrize('T', test_t_list)
145
+ @pytest.mark.parametrize('H', test_h_list)
146
+ @pytest.mark.parametrize('D', test_d_list)
147
+ @pytest.mark.parametrize('gate_logit_normalizer', test_gate_list)
148
+ @pytest.mark.parametrize('scale', [1])
149
+ @pytest.mark.parametrize('use_qk_l2norm_in_kernel', [True, False])
150
+ @pytest.mark.parametrize('dtype', [torch.float32, torch.float16])
151
+ @pytest.mark.skipif(
152
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
153
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
154
+ )
155
+ def test_recurrent_forward(
156
+ B: int,
157
+ T: int,
158
+ H: int,
159
+ D: int,
160
+ scale: float,
161
+ dtype: torch.dtype,
162
+ use_qk_l2norm_in_kernel: bool,
163
+ gate_logit_normalizer: float,
164
+ ):
165
+ torch.manual_seed(42)
166
+ q = torch.randn(B, T, H, D, dtype=torch.float32)
167
+ k = torch.randn(B, T, H, D, dtype=torch.float32)
168
+ v = torch.randn(B, T, H, D, dtype=dtype)
169
+ beta = torch.rand(B, T, H, dtype=dtype).sigmoid()
170
+ g = F.logsigmoid(torch.rand(B, T, H, dtype=torch.float32))
171
+ g = g / gate_logit_normalizer
172
+ h0 = torch.randn(B, H, D, D, dtype=torch.float32)
173
+ q, k, v, beta, g, h0 = map(lambda x: x.to(device).requires_grad_(), (q, k, v, beta, g, h0))
174
+ ref, ref_ht = recurrent_gated_delta_rule_ref(
175
+ q=F.normalize(q.clone(), p=2, dim=-1).to(dtype),
176
+ k=F.normalize(k.clone(), p=2, dim=-1).to(dtype),
177
+ v=v.clone(),
178
+ beta=beta.clone(),
179
+ g=g.clone(),
180
+ scale=scale,
181
+ initial_state=h0.clone(),
182
+ output_final_state=True,
183
+ )
184
+ tri, tri_ht = fused_recurrent_gated_delta_rule(
185
+ q=F.normalize(q.clone(), p=2, dim=-1).to(dtype) if not use_qk_l2norm_in_kernel else q.clone(),
186
+ k=F.normalize(k.clone(), p=2, dim=-1).to(dtype) if not use_qk_l2norm_in_kernel else k.clone(),
187
+ v=v.clone(),
188
+ beta=beta.clone(),
189
+ g=g.clone(),
190
+ scale=scale,
191
+ initial_state=h0.clone(),
192
+ use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
193
+ output_final_state=True,
194
+ )
195
+ assert_close(' o', ref, tri, 0.002)
196
+ assert_close(' ht', ref_ht, tri_ht, 0.002)
197
+
198
+
199
+ @pytest.mark.parametrize('B', test_b_list)
200
+ @pytest.mark.parametrize('T', test_t_list)
201
+ @pytest.mark.parametrize('H', test_h_list)
202
+ @pytest.mark.parametrize('D', test_d_list)
203
+ @pytest.mark.parametrize('gate_logit_normalizer', test_gate_list)
204
+ @pytest.mark.parametrize('scale', [1, 0.1])
205
+ @pytest.mark.parametrize('dtype', [torch.float16])
206
+ @pytest.mark.skipif(
207
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
208
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
209
+ )
210
+ def test_chunk(
211
+ B: int,
212
+ T: int,
213
+ H: int,
214
+ D: int,
215
+ dtype: torch.dtype,
216
+ scale: float,
217
+ gate_logit_normalizer: float
218
+ ):
219
+ if is_intel_alchemist and D > 128:
220
+ pytest.skip(reason='chunk_gated_delta_rule is not supported on alchemist for D>128')
221
+
222
+ q = torch.randn(B, T, H, D, dtype=dtype)
223
+ k = F.normalize(torch.randn(B, T, H, D, dtype=torch.float32), p=2, dim=-1).to(dtype)
224
+ v = torch.randn(B, T, H, D, dtype=dtype)
225
+ beta = torch.rand(B, T, H, dtype=dtype).sigmoid().fill_(1)
226
+ g = F.logsigmoid(torch.rand(B, T, H, dtype=torch.float32))
227
+ h0 = torch.zeros(B, H, D, D, dtype=torch.float32)
228
+ g = g / gate_logit_normalizer
229
+ q, k, v, beta, g, h0 = map(lambda x: x.to(device).requires_grad_(True), (q, k, v, beta, g, h0))
230
+
231
+ tri, tri_ht = chunk_gated_delta_rule(
232
+ q.clone(),
233
+ k.clone(),
234
+ v.clone(),
235
+ g.clone(),
236
+ beta.clone(),
237
+ scale=scale,
238
+ output_final_state=True,
239
+ initial_state=h0.clone(),
240
+ )
241
+ do = torch.randn_like(v)
242
+ dht = torch.randn_like(h0)
243
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward(retain_graph=True)
244
+ tri_dq, tri_dk, tri_dv, tri_dbeta, tri_dg, tri_dh0 = q.grad, k.grad, v.grad, beta.grad, g.grad, h0.grad
245
+ q.grad = k.grad = v.grad = beta.grad = g.grad = h0.grad = None
246
+
247
+ ref, ref_ht = chunk_gated_delta_rule_ref(
248
+ q.clone(),
249
+ k.clone(),
250
+ v.clone(),
251
+ g.clone(),
252
+ beta.clone(),
253
+ scale=scale,
254
+ output_final_state=True,
255
+ initial_state=h0.clone(),
256
+ )
257
+
258
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward(retain_graph=True)
259
+ ref_dq, ref_dk, ref_dv, ref_dbeta, ref_dg, ref_dh0 = q.grad, k.grad, v.grad, beta.grad, g.grad, h0.grad
260
+ assert_close(' o', ref, tri, 0.005)
261
+ assert_close(' ht', ref_ht, tri_ht, 0.005)
262
+ assert_close(' dq', ref_dq, tri_dq, 0.008)
263
+ assert_close(' dk', ref_dk, tri_dk, 0.008)
264
+ assert_close(' dv', ref_dv, tri_dv, 0.008)
265
+ assert_close(' db', ref_dbeta, tri_dbeta, 0.02)
266
+ if gate_logit_normalizer >= 1 and ref_dg.norm() > 0.01:
267
+ assert_close(' dg', ref_dg, tri_dg, 0.02)
268
+ assert_close('dh0', ref_dh0, tri_dh0, 0.008)
269
+
270
+
271
+ @pytest.mark.parametrize('N', test_b_list)
272
+ @pytest.mark.parametrize('T', test_t_varlen_list)
273
+ @pytest.mark.parametrize('H', test_h_list)
274
+ @pytest.mark.parametrize('D', test_d_list)
275
+ @pytest.mark.parametrize('scale', [1, 0.1])
276
+ @pytest.mark.parametrize('dtype', [torch.float16])
277
+ @pytest.mark.skipif(
278
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '1',
279
+ reason='Skipping test_chunk_varlen because SKIP_TEST_CHUNK_VARLEN is set'
280
+ )
281
+ def test_chunk_varlen(
282
+ N: int,
283
+ T: int,
284
+ H: int,
285
+ D: int,
286
+ scale: float,
287
+ dtype: torch.dtype,
288
+ ):
289
+ if is_intel_alchemist and D > 128:
290
+ pytest.skip(reason='chunk_gated_delta_rule is not supported on alchemist for D>128')
291
+ torch.manual_seed(42)
292
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
293
+ # randomly split the sequence into N segments
294
+ cu_seqlens = torch.cat([
295
+ torch.tensor([0], dtype=torch.long),
296
+ torch.arange(16, T)[torch.randperm(T - 16)[:N-1]],
297
+ torch.tensor([T], dtype=torch.long)
298
+ ], 0).to(device).sort()[0]
299
+ # seq-first required for inputs with variable lengths
300
+ q = torch.randn((1, T, H, D), dtype=dtype)
301
+ k = F.normalize(torch.randn(1, T, H, D, dtype=torch.float32), p=2, dim=-1).to(dtype)
302
+ v = torch.randn((1, T, H, D), dtype=dtype)
303
+ g = F.logsigmoid(torch.rand(1, T, H, dtype=dtype))
304
+ beta = torch.rand(1, T, H, dtype=dtype).sigmoid()
305
+ h0 = torch.randn((N, H, D, D), dtype=dtype)
306
+
307
+ q, k, v, beta, g, h0 = map(lambda x: x.to(device).requires_grad_(), (q, k, v, beta, g, h0))
308
+ do = torch.randn_like(v)
309
+ dht = torch.rand_like(h0)
310
+
311
+ tri, tri_ht = chunk_gated_delta_rule(
312
+ q=q.clone(),
313
+ k=k.clone(),
314
+ v=v.clone(),
315
+ beta=beta.clone(),
316
+ g=g.clone(),
317
+ scale=scale,
318
+ output_final_state=True,
319
+ initial_state=h0.clone(),
320
+ cu_seqlens=cu_seqlens,
321
+ )
322
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward(retain_graph=True)
323
+ tri_dq, tri_dk, tri_dv, tri_dbeta, tri_dg, tri_dh0 = q.grad, k.grad, v.grad, beta.grad, g.grad, h0.grad
324
+ q.grad = k.grad = v.grad = beta.grad = g.grad = h0.grad = None
325
+
326
+ ref = []
327
+ ref_ht = []
328
+ for i in range(N):
329
+ ref_i, ref_ht_i = recurrent_gated_delta_rule_ref(
330
+ q=q[:, cu_seqlens[i]:cu_seqlens[i+1]],
331
+ k=k[:, cu_seqlens[i]:cu_seqlens[i+1]],
332
+ v=v[:, cu_seqlens[i]:cu_seqlens[i+1]],
333
+ beta=beta[:, cu_seqlens[i]:cu_seqlens[i+1]],
334
+ g=g[:, cu_seqlens[i]:cu_seqlens[i+1]],
335
+ scale=scale,
336
+ initial_state=h0[i],
337
+ output_final_state=True,
338
+ )
339
+ ref.append(ref_i)
340
+ ref_ht.append(ref_ht_i)
341
+ ref = torch.cat(ref, 1)
342
+ ref_ht = torch.cat(ref_ht, 0)
343
+
344
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward(retain_graph=True)
345
+ ref_dq, ref_dk, ref_dv, ref_dbeta, ref_dg, ref_dh0 = q.grad, k.grad, v.grad, beta.grad, g.grad, h0.grad
346
+
347
+ assert_close(' o', ref, tri, 0.005)
348
+ assert_close(' ht', ref_ht, tri_ht, 0.005)
349
+ assert_close(' dq', ref_dq, tri_dq, 0.007)
350
+ assert_close(' dk', ref_dk, tri_dk, 0.008)
351
+ assert_close(' dv', ref_dv, tri_dv, 0.007)
352
+ assert_close(' db', ref_dbeta, tri_dbeta, 0.015)
353
+ assert_close(' dg', ref_dg, tri_dg, 0.015)
354
+ assert_close('dh0', ref_dh0, tri_dh0, 0.007)
upstream/flash-linear-attention/tests/ops/test_gla.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+
5
+ import pytest
6
+ import torch
7
+ import torch.nn.functional as F
8
+
9
+ from fla.ops.gla import chunk_gla, fused_recurrent_gla
10
+ from fla.ops.gla.naive import naive_recurrent_gla
11
+ from fla.utils import COMPILER_MODE, assert_close, device, device_platform
12
+
13
+ if COMPILER_MODE:
14
+ test_b_list = [1]
15
+ test_t_list = [4096]
16
+ test_t_varlen_list = test_t_list
17
+ test_d_list = [64, 128, 256]
18
+ test_gate_list = [1.0]
19
+ else:
20
+ test_b_list = [2]
21
+ test_t_list = [1, 15, 63, 300]
22
+ test_t_varlen_list = [63, 286, 300, 512]
23
+ test_d_list = [64, 32, 100, 256]
24
+ test_gate_list = [1, 0.1, 10]
25
+ test_h_list = [2]
26
+
27
+
28
+ @pytest.mark.parametrize('B', test_b_list)
29
+ @pytest.mark.parametrize('T', test_t_list)
30
+ @pytest.mark.parametrize('H', test_h_list)
31
+ @pytest.mark.parametrize('D', test_d_list)
32
+ @pytest.mark.parametrize('dtype', [torch.float])
33
+ @pytest.mark.skipif(
34
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
35
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
36
+ )
37
+ @pytest.mark.skipif(
38
+ device_platform == 'intel',
39
+ reason='Intel Triton Failure'
40
+ )
41
+ def test_fused_recurrent(
42
+ B: int,
43
+ T: int,
44
+ H: int,
45
+ D: int,
46
+ dtype: torch.dtype
47
+ ):
48
+ torch.manual_seed(42)
49
+
50
+ q = torch.randn((B, T, H, D), dtype=dtype, device=device).requires_grad_()
51
+ k = torch.randn((B, T, H, D), dtype=dtype, device=device).requires_grad_()
52
+ v = torch.randn((B, T, H, D), dtype=dtype, device=device).requires_grad_()
53
+ g = F.logsigmoid(torch.randn((B, T, H, D), dtype=dtype, device=device)).requires_grad_()
54
+ h0 = torch.randn(B, H, D, D, device=device).requires_grad_()
55
+
56
+ do = torch.randn_like(v)
57
+ ref, ref_ht = naive_recurrent_gla(
58
+ q=q,
59
+ k=k,
60
+ v=v,
61
+ gk=g,
62
+ initial_state=h0,
63
+ output_final_state=True
64
+ )
65
+ ((ref * do).sum()).backward()
66
+ ref_dq, q.grad = q.grad.clone(), None
67
+ ref_dk, k.grad = k.grad.clone(), None
68
+ ref_dv, v.grad = v.grad.clone(), None
69
+ ref_dg, g.grad = g.grad.clone(), None
70
+ ref_dh0, h0.grad = h0.grad.clone(), None
71
+
72
+ tri, tri_ht = fused_recurrent_gla(
73
+ q=q,
74
+ k=k,
75
+ v=v,
76
+ gk=g,
77
+ initial_state=h0,
78
+ output_final_state=True
79
+ )
80
+ ((tri * do).sum()).backward()
81
+ tri_dq, q.grad = q.grad.clone(), None
82
+ tri_dk, k.grad = k.grad.clone(), None
83
+ tri_dv, v.grad = v.grad.clone(), None
84
+ tri_dg, g.grad = g.grad.clone(), None
85
+ tri_dh0, h0.grad = h0.grad.clone(), None
86
+
87
+ assert_close(' o', ref, tri, 0.005)
88
+ assert_close(' ht', ref_ht, tri_ht, 0.005)
89
+ assert_close(' dq', ref_dq, tri_dq, 0.005)
90
+ assert_close(' dk', ref_dk, tri_dk, 0.005)
91
+ assert_close(' dv', ref_dv, tri_dv, 0.005)
92
+ assert_close(' dg', ref_dg, tri_dg, 0.005)
93
+ assert_close('dh0', ref_dh0, tri_dh0, 0.005)
94
+
95
+
96
+ @pytest.mark.parametrize('B', test_b_list)
97
+ @pytest.mark.parametrize('T', test_t_list)
98
+ @pytest.mark.parametrize('H', test_h_list)
99
+ @pytest.mark.parametrize('D', test_d_list)
100
+ @pytest.mark.parametrize('dtype', [torch.bfloat16])
101
+ @pytest.mark.parametrize('gate_logit_normalizer', test_gate_list)
102
+ @pytest.mark.skipif(
103
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
104
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
105
+ )
106
+ @pytest.mark.skipif(
107
+ device_platform == 'intel',
108
+ reason='Intel Triton Failure'
109
+ )
110
+ def test_chunk(
111
+ B: int,
112
+ T: int,
113
+ H: int,
114
+ D: int,
115
+ dtype: torch.dtype,
116
+ gate_logit_normalizer: float,
117
+ ):
118
+ torch.manual_seed(42)
119
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
120
+ # [B, T, H, D]
121
+ q = torch.randn((B, T, H, D), dtype=dtype, device=device).requires_grad_()
122
+ k = torch.randn((B, T, H, D), dtype=dtype, device=device).requires_grad_()
123
+ v = torch.randn((B, T, H, D), dtype=dtype, device=device).requires_grad_()
124
+ g = (F.logsigmoid(torch.randn((B, T, H, D), dtype=dtype, device=device)) / gate_logit_normalizer).requires_grad_()
125
+ h0 = torch.randn((B, H, D, D), dtype=dtype, device=device).requires_grad_()
126
+ do = torch.randn_like(v)
127
+ dht = torch.zeros((B, H, D, D), dtype=dtype, device=device)
128
+
129
+ tri, tri_ht = chunk_gla(
130
+ q,
131
+ k,
132
+ v,
133
+ g,
134
+ initial_state=h0,
135
+ output_final_state=True,
136
+ )
137
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward()
138
+ tri_dq, q.grad = q.grad.clone(), None
139
+ tri_dk, k.grad = k.grad.clone(), None
140
+ tri_dv, v.grad = v.grad.clone(), None
141
+ tri_dg, g.grad = g.grad.clone(), None
142
+ tri_dh0, h0.grad = h0.grad.clone(), None
143
+
144
+ ref, ref_ht = fused_recurrent_gla(
145
+ q,
146
+ k,
147
+ v,
148
+ g,
149
+ initial_state=h0,
150
+ output_final_state=True,
151
+ )
152
+ ref, _ = fused_recurrent_gla(
153
+ q,
154
+ k,
155
+ v,
156
+ g,
157
+ initial_state=h0,
158
+ output_final_state=False,
159
+ )
160
+ (ref * do).sum().backward()
161
+ ref_dq, q.grad = q.grad.clone(), None
162
+ ref_dk, k.grad = k.grad.clone(), None
163
+ ref_dv, v.grad = v.grad.clone(), None
164
+ ref_dg, g.grad = g.grad.clone(), None
165
+ ref_dh0, h0.grad = h0.grad.clone(), None
166
+
167
+ assert_close(' o', ref, tri, 0.004)
168
+ assert_close(' ht', ref_ht, tri_ht, 0.005)
169
+ assert_close(' dq', ref_dq, tri_dq, 0.005)
170
+ assert_close(' dk', ref_dk, tri_dk, 0.005)
171
+ assert_close(' dv', ref_dv, tri_dv, 0.005)
172
+ assert_close(' dg', ref_dg, tri_dg, 0.005)
173
+ assert_close('dh0', ref_dh0, tri_dh0, 0.005)
174
+
175
+
176
+ @pytest.mark.parametrize('N', test_b_list)
177
+ @pytest.mark.parametrize('T', test_t_varlen_list)
178
+ @pytest.mark.parametrize('H', test_h_list)
179
+ @pytest.mark.parametrize('D', test_d_list)
180
+ @pytest.mark.parametrize('dtype', [torch.bfloat16, torch.float])
181
+ @pytest.mark.skipif(
182
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '1',
183
+ reason='Skipping test_chunk_varlen because SKIP_TEST_CHUNK_VARLEN is set'
184
+ )
185
+ def test_chunk_varlen(
186
+ N: int,
187
+ T: int,
188
+ H: int,
189
+ D: int,
190
+ dtype: torch.dtype,
191
+ ):
192
+ torch.manual_seed(42)
193
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
194
+ # randomly split the sequence into N segments
195
+ cu_seqlens = torch.cat([
196
+ torch.tensor([0], dtype=torch.long),
197
+ torch.arange(16, T)[torch.randperm(T - 16)[:N-1]],
198
+ torch.tensor([T], dtype=torch.long)
199
+ ], 0).to(device).sort()[0]
200
+
201
+ q = torch.randn((1, T, H, D), dtype=dtype, device=device).requires_grad_()
202
+ k = torch.randn((1, T, H, D), dtype=dtype, device=device).requires_grad_()
203
+ v = torch.randn((1, T, H, D), dtype=dtype, device=device).requires_grad_()
204
+ g = F.logsigmoid(torch.randn((1, T, H, D), dtype=dtype, device=device)).requires_grad_()
205
+ h0 = torch.randn((N, H, D, D), dtype=dtype, device=device).requires_grad_()
206
+ do = torch.randn_like(v)
207
+
208
+ ref, ref_ht = fused_recurrent_gla(
209
+ q, k, v, g,
210
+ initial_state=h0,
211
+ output_final_state=True,
212
+ cu_seqlens=cu_seqlens
213
+ )
214
+ ref, _ = fused_recurrent_gla(
215
+ q, k, v, g,
216
+ initial_state=h0,
217
+ output_final_state=False,
218
+ cu_seqlens=cu_seqlens
219
+ )
220
+
221
+ (ref * do).sum().backward()
222
+ ref_dq, q.grad = q.grad.clone(), None
223
+ ref_dk, k.grad = k.grad.clone(), None
224
+ ref_dv, v.grad = v.grad.clone(), None
225
+ ref_dg, g.grad = g.grad.clone(), None
226
+ ref_dh0, h0.grad = h0.grad.clone(), None
227
+
228
+ tri, tri_ht = chunk_gla(
229
+ q,
230
+ k,
231
+ v,
232
+ g,
233
+ initial_state=h0,
234
+ output_final_state=True,
235
+ cu_seqlens=cu_seqlens
236
+ )
237
+ ((tri * do).sum()).backward()
238
+ tri_dq, q.grad = q.grad.clone(), None
239
+ tri_dk, k.grad = k.grad.clone(), None
240
+ tri_dv, v.grad = v.grad.clone(), None
241
+ tri_dg, g.grad = g.grad.clone(), None
242
+ tri_dh0, h0.grad = h0.grad.clone(), None
243
+
244
+ assert_close(' o', ref, tri, 0.004)
245
+ assert_close(' ht', ref_ht, tri_ht, 0.005)
246
+ assert_close(' dq', ref_dq, tri_dq, 0.005)
247
+ assert_close(' dk', ref_dk, tri_dk, 0.005)
248
+ assert_close(' dv', ref_dv, tri_dv, 0.005)
249
+ assert_close(' dg', ref_dg, tri_dg, 0.005)
250
+ assert_close('dh0', ref_dh0, tri_dh0, 0.005)
upstream/flash-linear-attention/tests/ops/test_nsa.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+
5
+ import pytest
6
+ import torch
7
+ import triton
8
+
9
+ from fla.ops.nsa.naive import naive_nsa
10
+ from fla.ops.nsa.parallel import parallel_nsa
11
+ from fla.ops.utils import prepare_token_indices
12
+ from fla.utils import COMPILER_MODE, assert_close, device
13
+
14
+ if COMPILER_MODE:
15
+ test_b_list = [1]
16
+ test_t_list = [4096]
17
+ test_t_varlen_list = test_t_list
18
+ else:
19
+ test_b_list = [2]
20
+ test_t_list = [256, 1024, 2000]
21
+ test_t_varlen_list = [63, 286, 300, 512]
22
+ test_h_list = [2]
23
+
24
+
25
+ # FIXME
26
+ @pytest.mark.parametrize('B', test_b_list)
27
+ @pytest.mark.parametrize('T', test_t_list)
28
+ @pytest.mark.parametrize('H', test_h_list)
29
+ @pytest.mark.parametrize('HQ', [64])
30
+ @pytest.mark.parametrize('D', [100, 64])
31
+ @pytest.mark.parametrize('S', [16])
32
+ @pytest.mark.parametrize('block_size', [32])
33
+ @pytest.mark.parametrize('dtype', [torch.float16])
34
+ @pytest.mark.parametrize('scale', [0.1])
35
+ @pytest.mark.skipif(
36
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
37
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
38
+ )
39
+ @pytest.mark.skipif(
40
+ True,
41
+ reason='TBD'
42
+ )
43
+ def test_parallel(
44
+ B: int,
45
+ H: int,
46
+ HQ: int,
47
+ T: int,
48
+ D: int,
49
+ S: int,
50
+ block_size: int,
51
+ dtype: torch.dtype,
52
+ scale: float
53
+ ):
54
+ torch.manual_seed(42)
55
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
56
+
57
+ q = torch.randn((B, T, HQ, D), dtype=dtype, device=device).requires_grad_(True)
58
+ k = torch.randn((B, T, H, D), dtype=dtype, device=device).requires_grad_(True)
59
+ v = torch.randn((B, T, H, D), dtype=dtype, device=device).requires_grad_(True)
60
+ do = torch.randn((B, T, HQ, D), dtype=dtype, device=device)
61
+
62
+ block_indices = torch.full((B, T, H, S), T, dtype=torch.long, device=device)
63
+ for b in range(B):
64
+ for t in range(T):
65
+ for h in range(H):
66
+ i_i = torch.randperm(max(1, triton.cdiv(t, block_size)))[:S]
67
+ block_indices[b, t, h, :len(i_i)] = i_i
68
+ block_indices = block_indices.sort(-1)[0]
69
+
70
+ ref = naive_nsa(q=q, k=k, v=v, block_indices=block_indices, block_size=block_size, scale=scale)
71
+ ref.backward(do)
72
+ ref_dq, q.grad = q.grad.clone(), None
73
+ ref_dk, k.grad = k.grad.clone(), None
74
+ ref_dv, v.grad = v.grad.clone(), None
75
+
76
+ tri = parallel_nsa(q=q, k=k, v=v, block_indices=block_indices, block_size=block_size, scale=scale)
77
+ tri.backward(do)
78
+ tri_dq, q.grad = q.grad.clone(), None
79
+ tri_dk, k.grad = k.grad.clone(), None
80
+ tri_dv, v.grad = v.grad.clone(), None
81
+
82
+ assert_close(" o", ref, tri, 0.005)
83
+ assert_close("dq", ref_dq, tri_dq, 0.005)
84
+ assert_close("dk", ref_dk, tri_dk, 0.005)
85
+ assert_close("dv", ref_dv, tri_dv, 0.005)
86
+
87
+
88
+ @pytest.mark.parametrize('N', test_b_list)
89
+ @pytest.mark.parametrize('T', test_t_varlen_list)
90
+ @pytest.mark.parametrize('H', test_h_list)
91
+ @pytest.mark.parametrize('HQ', [64])
92
+ @pytest.mark.parametrize('D', [100, 64])
93
+ @pytest.mark.parametrize('S', [16])
94
+ @pytest.mark.parametrize('block_size', [32])
95
+ @pytest.mark.parametrize('dtype', [torch.bfloat16])
96
+ @pytest.mark.skipif(
97
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '1',
98
+ reason='Skipping test because SKIP_TEST_CHUNK_VARLEN is set'
99
+ )
100
+ @pytest.mark.skipif(
101
+ True,
102
+ reason='TBD'
103
+ )
104
+ def test_parallel_varlen(
105
+ N: int,
106
+ T: int,
107
+ H: int,
108
+ HQ: int,
109
+ D: int,
110
+ S: int,
111
+ block_size: int,
112
+ dtype: torch.dtype,
113
+ ):
114
+ torch.manual_seed(42)
115
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
116
+
117
+ # randomly split the sequence into N segments
118
+ cu_seqlens = torch.cat([
119
+ torch.tensor([0], dtype=torch.long),
120
+ torch.arange(16, T)[torch.randperm(T - 16)[:N-1]],
121
+ torch.tensor([T], dtype=torch.long)
122
+ ], 0).to(device).sort()[0]
123
+ # seq-first required for inputs with variable lengths
124
+ q = torch.randn((1, T, HQ, D), dtype=dtype, device=device).requires_grad_()
125
+ k = torch.randn((1, T, H, D), dtype=dtype, device=device).requires_grad_()
126
+ v = torch.randn((1, T, H, D), dtype=dtype, device=device).requires_grad_()
127
+ do = torch.randn((1, T, HQ, D), dtype=dtype, device=device)
128
+
129
+ block_indices = torch.full((1, T, H, S), T, dtype=torch.long, device=device)
130
+ seq_indices = prepare_token_indices(cu_seqlens).tolist()
131
+
132
+ for i in range(T):
133
+ _, t = seq_indices[i]
134
+ for h in range(H):
135
+ i_i = torch.randperm(max(1, triton.cdiv(t, block_size)))[:S]
136
+ block_indices[0, i, h, :len(i_i)] = i_i
137
+ block_indices = block_indices.sort(-1)[0]
138
+
139
+ ref = naive_nsa(
140
+ q=q,
141
+ k=k,
142
+ v=v,
143
+ block_indices=block_indices,
144
+ block_size=block_size,
145
+ cu_seqlens=cu_seqlens
146
+ )
147
+ ref.backward(do)
148
+ ref_dq, q.grad = q.grad.clone(), None
149
+ ref_dk, k.grad = k.grad.clone(), None
150
+ ref_dv, v.grad = v.grad.clone(), None
151
+
152
+ tri = parallel_nsa(
153
+ q=q,
154
+ k=k,
155
+ v=v,
156
+ block_indices=block_indices,
157
+ block_size=block_size,
158
+ cu_seqlens=cu_seqlens
159
+ )
160
+ tri.backward(do)
161
+ tri_dq, q.grad = q.grad.clone(), None
162
+ tri_dk, k.grad = k.grad.clone(), None
163
+ tri_dv, v.grad = v.grad.clone(), None
164
+
165
+ assert_close(' o', ref, tri, 0.004)
166
+ assert_close('dq', ref_dq, tri_dq, 0.005)
167
+ assert_close('dk', ref_dk, tri_dk, 0.005)
168
+ assert_close('dv', ref_dv, tri_dv, 0.005)
upstream/flash-linear-attention/tests/ops/test_retention.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+
5
+ import pytest
6
+ import torch
7
+
8
+ from fla.ops.retention import chunk_retention, fused_recurrent_retention, parallel_retention
9
+ from fla.ops.retention.naive import naive_retention
10
+ from fla.utils import COMPILER_MODE, assert_close, device
11
+
12
+ if COMPILER_MODE:
13
+ test_b_list = [1]
14
+ test_t_list = [4096]
15
+ test_t_varlen_list = test_t_list
16
+ test_d_list = [64, 32, 100]
17
+ else:
18
+ test_b_list = [2]
19
+ test_t_list = [1, 15, 63, 300]
20
+ test_t_varlen_list = [63, 286, 300, 512]
21
+ test_d_list = [64, 32, 100]
22
+ test_h_list = [2]
23
+
24
+
25
+ @pytest.mark.parametrize('B', test_b_list)
26
+ @pytest.mark.parametrize('T', test_t_list)
27
+ @pytest.mark.parametrize('H', test_h_list)
28
+ @pytest.mark.parametrize('K', test_d_list)
29
+ @pytest.mark.parametrize('expand_ratio', [1, 2])
30
+ @pytest.mark.parametrize('dtype', [torch.float16])
31
+ @pytest.mark.skipif(
32
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
33
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
34
+ )
35
+ def test_chunk(
36
+ B: int,
37
+ T: int,
38
+ H: int,
39
+ K: int,
40
+ expand_ratio: int,
41
+ dtype: torch.dtype
42
+ ):
43
+ torch.manual_seed(42)
44
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
45
+ V = K * expand_ratio
46
+
47
+ q = torch.randn((B, T, H, K), dtype=dtype, device=device).requires_grad_()
48
+ k = torch.randn((B, T, H, K), dtype=dtype, device=device).requires_grad_()
49
+ v = torch.randn((B, T, H, V), dtype=dtype, device=device).requires_grad_()
50
+ h0 = torch.randn((B, H, K, V), dtype=dtype, device=device).requires_grad_()
51
+
52
+ do = torch.randn_like(v)
53
+ dht = torch.randn_like(h0)
54
+ ref, ref_ht = fused_recurrent_retention(q, k, v, initial_state=h0, output_final_state=True)
55
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward()
56
+ ref_dq, q.grad = q.grad.clone(), None
57
+ ref_dk, k.grad = k.grad.clone(), None
58
+ ref_dv, v.grad = v.grad.clone(), None
59
+
60
+ tri, tri_ht = chunk_retention(q, k, v, initial_state=h0, output_final_state=True)
61
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward()
62
+ tri_dq, q.grad = q.grad.clone(), None
63
+ tri_dk, k.grad = k.grad.clone(), None
64
+ tri_dv, v.grad = v.grad.clone(), None
65
+
66
+ assert_close(' o', ref, tri, 0.005)
67
+ assert_close('ht', ref_ht, tri_ht, 0.005)
68
+ assert_close('dq', ref_dq, tri_dq, 0.005)
69
+ assert_close('dk', ref_dk, tri_dk, 0.005)
70
+ assert_close('dv', ref_dv, tri_dv, 0.005)
71
+
72
+
73
+ @pytest.mark.parametrize('N', test_b_list)
74
+ @pytest.mark.parametrize('T', test_t_varlen_list)
75
+ @pytest.mark.parametrize('H', test_h_list)
76
+ @pytest.mark.parametrize('K', test_d_list)
77
+ @pytest.mark.parametrize('expand_ratio', [1, 2])
78
+ @pytest.mark.parametrize('dtype', [torch.float16])
79
+ @pytest.mark.skipif(
80
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '1',
81
+ reason='Skipping test_chunk_varlen because SKIP_TEST_CHUNK_VARLEN is set'
82
+ )
83
+ def test_chunk_varlen(
84
+ N: int,
85
+ T: int,
86
+ H: int,
87
+ K: int,
88
+ expand_ratio: int,
89
+ dtype: torch.dtype,
90
+ ):
91
+ torch.manual_seed(42)
92
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
93
+ V = K * expand_ratio
94
+
95
+ # randomly split the sequence into N segments
96
+ offsets = torch.cat([
97
+ torch.tensor([0], dtype=torch.long),
98
+ torch.arange(16, T)[torch.randperm(T - 16)[:N-1]],
99
+ torch.tensor([T], dtype=torch.long)
100
+ ], 0).to(device).sort()[0]
101
+ # seq-first required for inputs with variable lengths
102
+ q = torch.randn((1, T, H, K), dtype=dtype, device=device).requires_grad_()
103
+ k = torch.randn((1, T, H, K), dtype=dtype, device=device).requires_grad_()
104
+ v = torch.randn((1, T, H, V), dtype=dtype, device=device).requires_grad_()
105
+ h0 = torch.randn((N, H, K, V), dtype=dtype, device=device).requires_grad_()
106
+ do = torch.randn_like(v)
107
+ dht = torch.randn_like(h0)
108
+
109
+ ref, ref_ht = fused_recurrent_retention(
110
+ q=q,
111
+ k=k,
112
+ v=v,
113
+ initial_state=h0,
114
+ output_final_state=True,
115
+ cu_seqlens=offsets,
116
+ )
117
+ ((ref * do).sum() + (ref_ht * dht).sum()).backward()
118
+ ref_dq, q.grad = q.grad.clone(), None
119
+ ref_dk, k.grad = k.grad.clone(), None
120
+ ref_dv, v.grad = v.grad.clone(), None
121
+ ref_dh0, h0.grad = h0.grad.clone(), None
122
+
123
+ tri, tri_ht = chunk_retention(
124
+ q=q,
125
+ k=k,
126
+ v=v,
127
+ initial_state=h0,
128
+ output_final_state=True,
129
+ cu_seqlens=offsets,
130
+ )
131
+ ((tri * do).sum() + (tri_ht * dht).sum()).backward()
132
+ tri_dq, q.grad = q.grad.clone(), None
133
+ tri_dk, k.grad = k.grad.clone(), None
134
+ tri_dv, v.grad = v.grad.clone(), None
135
+ tri_dh0, h0.grad = h0.grad.clone(), None
136
+
137
+ assert_close(' o', ref, tri, 0.004)
138
+ assert_close(' ht', ref_ht, tri_ht, 0.005)
139
+ assert_close(' dq', ref_dq, tri_dq, 0.005)
140
+ assert_close(' dk', ref_dk, tri_dk, 0.005)
141
+ assert_close(' dv', ref_dv, tri_dv, 0.005)
142
+ assert_close('dh0', ref_dh0, tri_dh0, 0.005)
143
+
144
+
145
+ @pytest.mark.parametrize('B', test_b_list)
146
+ @pytest.mark.parametrize('T', test_t_list)
147
+ @pytest.mark.parametrize('H', test_h_list)
148
+ @pytest.mark.parametrize('K', test_d_list)
149
+ @pytest.mark.parametrize('expand_ratio', [1, 2])
150
+ @pytest.mark.parametrize('dtype', [torch.float16])
151
+ @pytest.mark.skipif(
152
+ os.getenv('SKIP_TEST_CHUNK_VARLEN') == '0',
153
+ reason='Skipping test because TEST_CHUNK_VARLEN is enabled'
154
+ )
155
+ def test_parallel(
156
+ B: int,
157
+ T: int,
158
+ H: int,
159
+ K: int,
160
+ expand_ratio: int,
161
+ dtype: torch.dtype
162
+ ):
163
+ torch.manual_seed(42)
164
+ V = K * expand_ratio
165
+
166
+ q = torch.randn((B, T, H, K), dtype=dtype, device=device).requires_grad_()
167
+ k = torch.randn((B, T, H, K), dtype=dtype, device=device).requires_grad_()
168
+ v = torch.randn((B, T, H, V), dtype=dtype, device=device).requires_grad_()
169
+ do = torch.randn_like(v)
170
+
171
+ ref = naive_retention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)).transpose(1, 2)
172
+ ref.backward(do)
173
+ ref_dq, q.grad = q.grad.clone(), None
174
+ ref_dk, k.grad = k.grad.clone(), None
175
+ ref_dv, v.grad = v.grad.clone(), None
176
+
177
+ tri, _ = parallel_retention(q, k, v)
178
+ tri.backward(do)
179
+ tri_dq, q.grad = q.grad.clone(), None
180
+ tri_dk, k.grad = k.grad.clone(), None
181
+ tri_dv, v.grad = v.grad.clone(), None
182
+
183
+ assert_close(' o', ref, tri, 0.005)
184
+ assert_close('dq', ref_dq, tri_dq, 0.005)
185
+ assert_close('dk', ref_dk, tri_dk, 0.005)
186
+ assert_close('dv', ref_dv, tri_dv, 0.005)
upstream/flash-linear-attention/tests/ops/test_ttt.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+
5
+ import pytest
6
+ import torch
7
+ import torch.nn.functional as F
8
+
9
+ from fla.ops.ttt import chunk_ttt_linear, fused_chunk_ttt_linear
10
+ from fla.ops.ttt.naive import chunk_ttt_linear_ref
11
+ from fla.utils import COMPILER_MODE, assert_close, check_shared_mem, device
12
+
13
+ if COMPILER_MODE:
14
+ test_b_list = [1]
15
+ test_t_list = [4096]
16
+ test_t_varlen_list = test_t_list
17
+ test_d_list = [64, 128]
18
+ else:
19
+ test_b_list = [2]
20
+ test_t_list = [1, 15, 63, 300]
21
+ test_t_varlen_list = [63, 286, 300, 512]
22
+ test_d_list = [50, 64, 100, 128]
23
+ test_h_list = [2]
24
+
25
+
26
+ @pytest.mark.parametrize("B", test_b_list)
27
+ @pytest.mark.parametrize("T", test_t_list)
28
+ @pytest.mark.parametrize("H", test_h_list)
29
+ @pytest.mark.parametrize("D", test_d_list)
30
+ @pytest.mark.parametrize("scale", [0.1])
31
+ @pytest.mark.parametrize("dtype", [torch.float16])
32
+ @pytest.mark.parametrize("head_first", [True, False])
33
+ @pytest.mark.skipif(
34
+ os.getenv("SKIP_TEST_CHUNK_VARLEN") == "0",
35
+ reason="Skipping test because TEST_CHUNK_VARLEN is enabled"
36
+ )
37
+ def test_chunk(
38
+ B: int,
39
+ T: int,
40
+ H: int,
41
+ D: int,
42
+ dtype: torch.dtype,
43
+ scale: float,
44
+ head_first: bool
45
+ ):
46
+ if D > 64 and check_shared_mem('hopper') is False:
47
+ pytest.skip(reason="Current CI do not support this config")
48
+ eta_base = 5e-3
49
+ if head_first:
50
+ q = torch.randn(B, H, T, D, dtype=dtype)
51
+ k = F.normalize(torch.randn(B, H, T, D, dtype=torch.float32), p=2, dim=-1).to(dtype)
52
+ v = torch.randn(B, H, T, D, dtype=dtype)
53
+ w = torch.randn(H, D, dtype=dtype)
54
+ b = torch.randn(H, D, dtype=dtype)
55
+ eta = torch.randn(B, H, T, 1, dtype=dtype) * eta_base
56
+ h0 = torch.randn(B, H, D, D, dtype=torch.float32)
57
+ hb0 = torch.randn(B, H, 1, D, dtype=torch.float32)
58
+ else:
59
+ q = torch.randn(B, T, H, D, dtype=dtype)
60
+ k = F.normalize(torch.randn(B, T, H, D, dtype=torch.float32), p=2, dim=-1).to(dtype)
61
+ v = torch.randn(B, T, H, D, dtype=dtype)
62
+ w = torch.randn(H, D, dtype=dtype)
63
+ b = torch.randn(H, D, dtype=dtype)
64
+ eta = torch.randn(B, T, H, 1, dtype=dtype) * eta_base
65
+ h0 = torch.randn(B, H, D, D, dtype=torch.float32)
66
+ hb0 = torch.randn(B, H, 1, D, dtype=torch.float32)
67
+
68
+ q, k, v, w, b, eta, h0, hb0 = map(lambda x: x.to(device).requires_grad_(True), (q, k, v, w, b, eta, h0, hb0))
69
+ do = torch.rand_like(v)
70
+ dht = torch.rand_like(h0)
71
+ dhbt = torch.rand_like(hb0)
72
+
73
+ tri, tri_ht, tri_hbt = chunk_ttt_linear(
74
+ q.clone(),
75
+ k.clone(),
76
+ v.clone(),
77
+ w.clone(),
78
+ b.clone(),
79
+ eta.clone(),
80
+ scale=scale,
81
+ output_final_state=True,
82
+ initial_state=h0.clone(),
83
+ initial_state_bias=hb0.clone(),
84
+ head_first=head_first
85
+ )
86
+ ((tri * do).sum() + (tri_ht * dht).sum() + (tri_hbt * dhbt).sum()).backward(retain_graph=True)
87
+ tri_dq, tri_dk, tri_dv, tri_dw, tri_db, tri_deta, \
88
+ tri_dh0, tri_dhb0 = q.grad, k.grad, v.grad, w.grad, b.grad, eta.grad, h0.grad, hb0.grad
89
+ q.grad = k.grad = v.grad = w.grad = b.grad = eta.grad = h0.grad = hb0.grad = None
90
+
91
+ ref, ref_ht, ref_hbt = chunk_ttt_linear_ref(
92
+ q.clone(),
93
+ k.clone(),
94
+ v.clone(),
95
+ w.clone(),
96
+ b.clone(),
97
+ eta.clone(),
98
+ scale=scale,
99
+ output_final_state=True,
100
+ initial_state=h0.clone(),
101
+ initial_state_bias=hb0.clone(),
102
+ head_first=head_first
103
+ )
104
+ ((ref * do).sum() + (ref_ht * dht).sum() + (ref_hbt * dhbt).sum()).backward(retain_graph=True)
105
+ ref_dq, ref_dk, ref_dv, ref_dw, ref_db, ref_deta, \
106
+ ref_dh0, ref_dhb0 = q.grad, k.grad, v.grad, w.grad, b.grad, eta.grad, h0.grad, hb0.grad
107
+
108
+ assert_close(" o", ref, tri, 0.005)
109
+ assert_close(" ht", ref_ht, tri_ht, 0.005)
110
+ assert_close(" hbt", ref_hbt, tri_hbt, 0.005)
111
+ assert_close(" dq", ref_dq, tri_dq, 0.005)
112
+ assert_close(" dk", ref_dk, tri_dk, 0.010)
113
+ assert_close(" dv", ref_dv, tri_dv, 0.007)
114
+ assert_close(" dw", ref_dw, tri_dw, 0.006)
115
+ assert_close(" db", ref_db, tri_db, 0.006)
116
+ assert_close(" de", ref_deta, tri_deta, 0.030) # because the last element of the chunk
117
+ if head_first:
118
+ assert_close(" de0", ref_deta[:, :, :14, :], tri_deta[:, :, :14, :], 0.010)
119
+ else:
120
+ assert_close(" de0", ref_deta[:, :14, :, :], tri_deta[:, :14, :, :], 0.010)
121
+ assert_close(" dh0", ref_dh0, tri_dh0, 0.007)
122
+ assert_close("dhb0", ref_dhb0, tri_dhb0, 0.005)
123
+
124
+
125
+ @pytest.mark.parametrize("B", test_b_list)
126
+ @pytest.mark.parametrize("T", test_t_list)
127
+ @pytest.mark.parametrize("H", test_h_list)
128
+ @pytest.mark.parametrize("D", test_d_list)
129
+ @pytest.mark.parametrize("scale", [0.1])
130
+ @pytest.mark.parametrize("dtype", [torch.float16])
131
+ @pytest.mark.parametrize("head_first", [True, False])
132
+ @pytest.mark.skipif(
133
+ os.getenv("SKIP_TEST_CHUNK_VARLEN") == "0",
134
+ reason="Skipping test because TEST_CHUNK_VARLEN is enabled"
135
+ )
136
+ def test_fused_chunk_fwd(
137
+ B: int,
138
+ T: int,
139
+ H: int,
140
+ D: int,
141
+ dtype: torch.dtype,
142
+ scale: float,
143
+ head_first: bool
144
+ ):
145
+ if D > 64 and check_shared_mem('hopper') is False:
146
+ pytest.skip(reason="Current CI do not support this config")
147
+ eta_base = 5e-3
148
+ if head_first:
149
+ q = torch.randn(B, H, T, D, dtype=dtype)
150
+ k = F.normalize(torch.randn(B, H, T, D, dtype=torch.float32), p=2, dim=-1).to(dtype)
151
+ v = torch.randn(B, H, T, D, dtype=dtype)
152
+ w = torch.randn(H, D, dtype=dtype)
153
+ b = torch.randn(H, D, dtype=dtype)
154
+ eta = torch.randn(B, H, T, 1, dtype=dtype) * eta_base
155
+ h0 = torch.randn(B, H, D, D, dtype=torch.float32)
156
+ hb0 = torch.randn(B, H, 1, D, dtype=torch.float32)
157
+ else:
158
+ q = torch.randn(B, T, H, D, dtype=dtype)
159
+ k = F.normalize(torch.randn(B, T, H, D, dtype=torch.float32), p=2, dim=-1).to(dtype)
160
+ v = torch.randn(B, T, H, D, dtype=dtype)
161
+ w = torch.randn(H, D, dtype=dtype)
162
+ b = torch.randn(H, D, dtype=dtype)
163
+ eta = torch.randn(B, T, H, 1, dtype=dtype) * eta_base
164
+ h0 = torch.randn(B, H, D, D, dtype=torch.float32)
165
+ hb0 = torch.randn(B, H, 1, D, dtype=torch.float32)
166
+
167
+ q, k, v, w, b, eta, h0, hb0 = map(lambda x: x.to(device).requires_grad_(True), (q, k, v, w, b, eta, h0, hb0))
168
+ do = torch.rand_like(v)
169
+ dht = torch.rand_like(h0)
170
+ dhbt = torch.rand_like(hb0)
171
+
172
+ tri, tri_ht, tri_hbt = fused_chunk_ttt_linear(
173
+ q.clone(),
174
+ k.clone(),
175
+ v.clone(),
176
+ w.clone(),
177
+ b.clone(),
178
+ eta.clone(),
179
+ scale=scale,
180
+ output_final_state=True,
181
+ initial_state=h0.clone(),
182
+ initial_state_bias=hb0.clone(),
183
+ head_first=head_first
184
+ )
185
+ ((tri * do).sum() + (tri_ht * dht).sum() + (tri_hbt * dhbt).sum()).backward(retain_graph=True)
186
+ tri_dq, tri_dk, tri_dv, tri_dw, tri_db, tri_deta, \
187
+ tri_dh0, tri_dhb0 = q.grad, k.grad, v.grad, w.grad, b.grad, eta.grad, h0.grad, hb0.grad
188
+ q.grad = k.grad = v.grad = w.grad = b.grad = eta.grad = h0.grad = hb0.grad = None
189
+
190
+ ref, ref_ht, ref_hbt = chunk_ttt_linear_ref(
191
+ q.clone(),
192
+ k.clone(),
193
+ v.clone(),
194
+ w.clone(),
195
+ b.clone(),
196
+ eta.clone(),
197
+ scale=scale,
198
+ output_final_state=True,
199
+ initial_state=h0.clone(),
200
+ initial_state_bias=hb0.clone(),
201
+ head_first=head_first
202
+ )
203
+ ((ref * do).sum() + (ref_ht * dht).sum() + (ref_hbt * dhbt).sum()).backward(retain_graph=True)
204
+ ref_dq, ref_dk, ref_dv, ref_dw, ref_db, ref_deta, \
205
+ ref_dh0, ref_dhb0 = q.grad, k.grad, v.grad, w.grad, b.grad, eta.grad, h0.grad, hb0.grad
206
+
207
+ assert_close(" o", ref, tri, 0.005)
208
+ assert_close(" ht", ref_ht, tri_ht, 0.005)
209
+ assert_close(" hbt", ref_hbt, tri_hbt, 0.005)
210
+ assert_close(" dq", ref_dq, tri_dq, 0.005)
211
+ assert_close(" dk", ref_dk, tri_dk, 0.010)
212
+ assert_close(" dv", ref_dv, tri_dv, 0.007)
213
+ assert_close(" dw", ref_dw, tri_dw, 0.005)
214
+ assert_close(" db", ref_db, tri_db, 0.005)
215
+ assert_close(" de", ref_deta, tri_deta, 0.03) # because the last element of the chunk
216
+ if head_first:
217
+ assert_close(" de0", ref_deta[:, :, :14, :], tri_deta[:, :, :14, :], 0.008)
218
+ else:
219
+ assert_close(" de0", ref_deta[:, :14, :, :], tri_deta[:, :14, :, :], 0.008)
220
+ assert_close(" dh0", ref_dh0, tri_dh0, 0.006)
221
+ assert_close("dhb0", ref_dhb0, tri_dhb0, 0.005)
222
+
223
+
224
+ @pytest.mark.parametrize("N", test_b_list)
225
+ @pytest.mark.parametrize("T", test_t_varlen_list)
226
+ @pytest.mark.parametrize("H", test_h_list)
227
+ @pytest.mark.parametrize("D", test_d_list)
228
+ @pytest.mark.parametrize("scale", [0.1])
229
+ @pytest.mark.parametrize("dtype", [torch.float16])
230
+ @pytest.mark.skipif(
231
+ os.getenv("SKIP_TEST_CHUNK_VARLEN") == "1",
232
+ reason="Skipping test_chunk_varlen because SKIP_TEST_CHUNK_VARLEN is set"
233
+ )
234
+ def test_chunk_varlen_fwd(
235
+ N: int,
236
+ T: int,
237
+ H: int,
238
+ D: int,
239
+ scale: float,
240
+ dtype: torch.dtype,
241
+ ):
242
+ if D > 64 and check_shared_mem('hopper') is False:
243
+ pytest.skip(reason="Current CI do not support this config")
244
+ torch.manual_seed(42)
245
+ os.environ['TRITON_F32_DEFAULT'] = 'ieee'
246
+ # randomly split the sequence into N segments
247
+ offsets = torch.cat([
248
+ torch.tensor([0], dtype=torch.long),
249
+ torch.arange(16, T)[torch.randperm(T - 1)[:N-1]],
250
+ torch.tensor([T], dtype=torch.long)
251
+ ], 0).to(device).sort()[0]
252
+ eta_base = 5e-3
253
+ # seq-first required for inputs with variable lengths
254
+ q = torch.randn((1, T, H, D), dtype=dtype)
255
+ k = F.normalize(torch.randn(1, T, H, D, dtype=torch.float32), p=2, dim=-1).to(dtype)
256
+ v = torch.randn((1, T, H, D), dtype=dtype)
257
+ eta = torch.randn(1, T, H, 1, dtype=dtype) * eta_base
258
+ w = torch.randn(H, D, dtype=dtype)
259
+ b = torch.randn(H, D, dtype=dtype)
260
+ h0 = torch.randn((N, H, D, D), dtype=torch.float32)
261
+ hb0 = torch.randn((N, H, 1, D), dtype=torch.float32)
262
+ q, k, v, w, b, eta, h0, hb0 = map(lambda x: x.to(device).requires_grad_(), (q, k, v, w, b, eta, h0, hb0))
263
+
264
+ tri, tri_ht, tri_hbt = chunk_ttt_linear(
265
+ q.clone(),
266
+ k.clone(),
267
+ v.clone(),
268
+ w.clone(),
269
+ b.clone(),
270
+ eta.clone(),
271
+ scale=scale,
272
+ output_final_state=True,
273
+ initial_state=h0.clone(),
274
+ initial_state_bias=hb0.clone(),
275
+ cu_seqlens=offsets,
276
+ head_first=False
277
+ )
278
+
279
+ ref = []
280
+ ref_ht = []
281
+ ref_hbt = []
282
+ for i in range(N):
283
+ ref_i, ref_ht_i, ref_hbt_i = chunk_ttt_linear_ref(
284
+ q=q[:, offsets[i]:offsets[i+1]],
285
+ k=k[:, offsets[i]:offsets[i+1]],
286
+ v=v[:, offsets[i]:offsets[i+1]],
287
+ w=w,
288
+ b=b,
289
+ eta=eta[:, offsets[i]:offsets[i+1]],
290
+ scale=scale,
291
+ initial_state=h0[i],
292
+ initial_state_bias=hb0[i],
293
+ output_final_state=True,
294
+ head_first=False
295
+ )
296
+ ref.append(ref_i)
297
+ ref_ht.append(ref_ht_i)
298
+ ref_hbt.append(ref_hbt_i)
299
+ ref = torch.cat(ref, 1)
300
+ ref_ht = torch.cat(ref_ht, 0)
301
+ ref_hbt = torch.cat(ref_hbt, 0)
302
+
303
+ assert_close(" o", ref, tri, 0.005)
304
+ assert_close(" ht", ref_ht, tri_ht, 0.005)
305
+ assert_close("hbt", ref_hbt, tri_hbt, 0.005)