Skip to content

Commit

Permalink
Use torch.nan_to_num replace numpy wrapper one (#5877)
Browse files Browse the repository at this point in the history
Co-authored-by: Logan Adams <[email protected]>
  • Loading branch information
jinyouzhi and loadams authored Aug 14, 2024
1 parent 0f2d485 commit 862aff3
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions deepspeed/runtime/eigenvalue.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from deepspeed.utils import log_dist
import numpy as np
import logging
from deepspeed.utils.torch import required_torch_version


class Eigenvalue(object):
Expand Down Expand Up @@ -36,12 +37,15 @@ def __init__(self,
ranks=[0])

# Replace all nan/pos-inf/neg-inf to zero
# TODO: Pytorch new version may add this function, replace this one by then.
def nan_to_num(self, x):
device = x.device
x = x.cpu().numpy()
x = np.nan_to_num(x=x, copy=False, nan=0.0, posinf=0.0, neginf=0.0)
return torch.from_numpy(x).to(device)
if required_torch_version(min_version=1.8):
return torch.nan_to_num(x, nan=0.0, posinf=0.0, neginf=0.0)
else:
# Fallback to numpy based implementation for backwards-compatibility with PyTorch 1.7 or older versions.
device = x.device
x = x.cpu().numpy()
x = np.nan_to_num(x=x, copy=False, nan=0.0, posinf=0.0, neginf=0.0)
return torch.from_numpy(x).to(device)

def normalize(self, v):
norm_squared = self.inner_product(v, v)
Expand Down

0 comments on commit 862aff3

Please sign in to comment.