Skip to content
Open
Show file tree
Hide file tree
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
7 changes: 4 additions & 3 deletions coremltools/converters/mil/frontend/torch/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -2029,9 +2029,10 @@ def _parse_keyword_args(context, node, rounding_mode) -> Var:
def floor_divide(context, node):
inputs = _get_inputs(context, node, expected=2)
inputs = promote_input_dtypes(inputs)
div_res = mb.floor_div(x=inputs[0], y=inputs[1])
# Pytorch's floor_divide always returns fp32, even if the inputs are int
res = mb.cast(x=div_res, dtype='fp32', name=node.name)
# PyTorch's floor_divide preserves the input dtype: int inputs produce an
# int result, float inputs produce a float result. Match that behavior
# rather than always casting to fp32.
res = mb.floor_div(x=inputs[0], y=inputs[1], name=node.name)
context.add(res)


Expand Down
30 changes: 30 additions & 0 deletions coremltools/converters/mil/frontend/torch/test/test_torch_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -6675,6 +6675,36 @@ def test_div(self, compute_unit, backend, frontend, rounding_mode, x2_type):
expected_results=out,
)

@pytest.mark.parametrize(
"compute_unit, backend, frontend, dtype",
itertools.product(
compute_units, backends, frontends, [np.float32, np.int32]
),
)
def test_floor_divide(self, compute_unit, backend, frontend, dtype):
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There probably a better place to put this unit test than under the TestActivation class.

model = ModuleWrapper(function=torch.floor_divide)
x1 = torch.from_numpy(np.array([10, -10, 7, -7], dtype=dtype))
x2 = torch.from_numpy(np.array([3, 3, 2, 2], dtype=dtype))
out = torch.floor_divide(x1, x2)
res = self.run_compare_torch(
[x1, x2],
model,
frontend=frontend,
backend=backend,
compute_unit=compute_unit,
input_as_shape=False,
expected_results=out,
)
# Pin output dtype: numerical comparison alone passes for both the
# always-fp32 and dtype-preserving paths, since [3,-4,3,-4] is
# representable in int32 and fp32 alike.
output_var = res[1]._mil_program.functions["main"].outputs[0]
expected_dtype = types.int32 if dtype == np.int32 else types.fp32
assert output_var.dtype == expected_dtype, (
f"floor_divide output dtype: expected {expected_dtype}, "
f"got {output_var.dtype} (input dtype was {dtype})"
)


class TestElementWiseUnary(TorchBaseTest):
@pytest.mark.parametrize(
Expand Down