Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add numerical correctness unittest and fix typo of PR[8041] #8044

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 46 additions & 5 deletions python/oneflow/test/modules/test_parital_fc.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,63 @@
from oneflow.test_utils.automated_test_util import *
import oneflow as flow
import oneflow.unittest
import numpy as np


@unittest.skipIf(os.getenv("ONEFLOW_TEST_CPU_ONLY"), "only test cpu cases")
class TestParitalFC(flow.unittest.TestCase):
def test_parital_fc(test_case):
class TestPartialFC(flow.unittest.TestCase):
def test_partial_fc(test_case):
p = flow.env.all_device_placement("cuda")
w = flow.randn(50000, 128, placement=p, sbp=flow.sbp.broadcast, requires_grad=True)
w = flow.randn(
50000, 128, placement=p, sbp=flow.sbp.broadcast, requires_grad=True
)
label = flow.randint(0, 50000, (512,), placement=p, sbp=flow.sbp.broadcast)
num_sample = 5000
out = flow.distributed_partial_fc_sample(w, label, num_sample)
test_case.assertTrue(out[0].shape == flow.Size([512]))
test_case.assertTrue(out[1].shape == flow.Size([5000]))
test_case.assertTrue(out[2].shape == flow.Size([5000, 128]))

# test gradient function
sample_weight = out[2]
sample_weight.sum().backward()
x = flow.randn(
512, 128, placement=p, sbp=flow.sbp.broadcast, requires_grad=True
)
_, sample_labels, sample_weights = out
flow.matmul(x, sample_weights, transpose_b=True).sum().backward()

# test numerical correctness
sample_mask = flow.BoolTensor(w.shape[0], placement=p, sbp=flow.sbp.broadcast)
sample_mask[:] = False
sample_mask[sample_labels] = True

test_case.assertTrue(
np.allclose(
w.grad[sample_labels].numpy(),
np.repeat(flow.sum(x, dim=0, keepdim=True).numpy(), num_sample, axis=0),
rtol=0.01,
atol=0.01,
)
)
test_case.assertTrue(
np.allclose(
w.grad[~sample_mask].numpy(),
np.zeros((w.shape[0] - num_sample, w.shape[1])),
rtol=0.0001,
atol=0.0001,
)
)
test_case.assertTrue(
np.allclose(
x.grad.numpy(),
np.repeat(
flow.sum(w[sample_labels], dim=0, keepdim=True).numpy(),
x.shape[0],
axis=0,
),
rtol=0.01,
atol=0.01,
)
)


if __name__ == "__main__":
Expand Down