update torch conditional import

This commit is contained in:
bluepulsar
2026-02-12 10:15:54 +08:00
parent af8aee402e
commit 233ae84103
4 changed files with 17 additions and 9 deletions
+8 -4
View File
@@ -25,11 +25,15 @@ class Tracker:
dis_preset = config_tracker["dis_preset"]
loop_closure_interval = config_tracker["loop_closure_interval"]
self.__algorithm = config_tracker["algorithm"]
# Conditionally import torch only if RAFT algorithm is used
self.torch = None
if self.__algorithm == "raft":
import torch
self.torch = torch
if self.__algorithm == "raft" and (not self.cuda or not torch.cuda.is_available()):
if self.__algorithm == "raft" and (not self.cuda or not self.torch.cuda.is_available()):
self.__algorithm = "dis"
if self.verbose:
print("No CUDA available, falling back to OPENCV DIS optical flow")
@@ -217,7 +221,7 @@ class Tracker:
frame = np.ascontiguousarray(frame)
# Upload to device as uint8 first to save bandwidth (4x less data than float32)
tensor = torch.from_numpy(frame).permute(2, 0, 1)
tensor = self.torch.from_numpy(frame).permute(2, 0, 1)
# Pin memory for faster CPU-GPU transfer (similar to DataLoader pin_memory=True)
if self.__raft_device == 'cuda':
@@ -258,9 +262,9 @@ class Tracker:
if self.verbose:
t0 = time.perf_counter()
with torch.inference_mode():
with self.torch.inference_mode():
if self.__raft_device == 'cuda':
with torch.amp.autocast('cuda'):
with self.torch.amp.autocast('cuda'):
flow = self.__raft_model(prev_tensor, curr_tensor)
else:
flow = self.__raft_model(prev_tensor, curr_tensor)