Repository navigation
Add MaskRandom #1166
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
Open
cedric-lorenz
wants to merge
1
commit into
main
Choose a base branch
from
clorenz/kumo-prior-04-mask-random
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add MaskRandom #1166
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| from collections.abc import Sequence | ||
| from typing import cast | ||
|
|
||
| import torch | ||
| from torch import Tensor | ||
|
|
||
|
|
||
| class SeedMixin: | ||
| r"""Store a seed at fit, from which transform draws its row values.""" | ||
|
|
||
| _seed = 0 | ||
|
|
||
| def get_extra_state(self) -> object: | ||
| r""":meta private:""" # noqa: D415 | ||
| return self._seed | ||
|
|
||
| def set_extra_state(self, state: object) -> None: | ||
| r""":meta private:""" # noqa: D415 | ||
| self._seed = cast(int, state) | ||
|
|
||
| def _draw_seed(self, generator: torch.Generator | None) -> None: | ||
| device = None if generator is None else generator.device | ||
| self._seed = int( | ||
| torch.randint(2**62, (), device=device, generator=generator) | ||
| ) | ||
|
|
||
| def _transform_generator(self) -> torch.Generator: | ||
| # A CPU generator makes the output independent of the device. | ||
| return torch.Generator().manual_seed(self._seed) | ||
|
|
||
|
|
||
| def uniform( | ||
| low: float, | ||
| high: float, | ||
| size: Sequence[int], | ||
| *, | ||
| device: torch.device, | ||
| dtype: torch.dtype, | ||
| generator: torch.Generator | None, | ||
| ) -> Tensor: | ||
| return torch.empty(size, device=device, dtype=dtype).uniform_( | ||
| low, high, generator=generator | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| """Processors that mask numerical and categorical cells.""" | ||
|
|
||
| from sdm.processing.missing.random import MaskRandom | ||
|
|
||
| __all__ = [ | ||
| "MaskRandom", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import torch | ||
| from torch import Tensor | ||
|
|
||
| from sdm import CategoricalTensor, TableTensor | ||
|
|
||
|
|
||
| def mask_cells(table: TableTensor, missing: Tensor) -> TableTensor: | ||
| r"""Mask numerical and categorical cells where ``missing`` is true.""" | ||
| num_numerical = table.numerical.size(-1) | ||
| code = table.categorical.code.masked_fill(missing[..., num_numerical:], -1) | ||
| return table.replace_blocks( | ||
| numerical=table.numerical.masked_fill( | ||
| missing[..., :num_numerical], torch.nan | ||
| ), | ||
| categorical=CategoricalTensor( | ||
| code=code, | ||
| categories=table.categorical.categories, | ||
| ), | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import torch | ||
| from torch import Tensor | ||
|
|
||
| from sdm import Stype, TableTensor | ||
| from sdm.processing import Processor | ||
| from sdm.processing._random import SeedMixin, uniform | ||
| from sdm.processing.missing._cells import mask_cells | ||
|
|
||
|
|
||
| class MaskRandom(SeedMixin, Processor): | ||
| """Mask numerical and categorical cells completely at random. | ||
|
|
||
| Each table draws a missing-cell probability when the processor is fitted. | ||
| Transform masks each cell independently with this probability. Apply the | ||
| processor to all rows in one call. | ||
|
|
||
| Args: | ||
| rate: Range from which to draw each table's missing-cell probability. | ||
| """ | ||
|
|
||
| handles_stypes = (Stype.numerical, Stype.categorical) | ||
| requires_fit = True | ||
|
|
||
| _missing_rate: Tensor | ||
|
|
||
| def __init__(self, *, rate: tuple[float, float] = (0.01, 0.08)) -> None: | ||
| super().__init__() | ||
| self.rate = rate | ||
| self.register_buffer("_missing_rate", torch.empty(0)) | ||
|
|
||
| def _fit( | ||
| self, | ||
| table: TableTensor, | ||
| *, | ||
| generator: torch.Generator | None = None, | ||
| ) -> None: | ||
| self._draw_seed(generator) | ||
| self._set_buffer( | ||
| "_missing_rate", | ||
| uniform( | ||
| low=self.rate[0], | ||
| high=self.rate[1], | ||
| size=table.size()[:-2], | ||
| device=table.device, | ||
| dtype=table.numerical.dtype, | ||
| generator=generator, | ||
| ), | ||
| ) | ||
|
|
||
| def _transform(self, table: TableTensor) -> TableTensor: | ||
| num_columns = table.numerical.size(-1) + table.categorical.size(-1) | ||
| u = torch.rand( | ||
| (*table.size()[:-1], num_columns), | ||
| generator=self._transform_generator(), | ||
| ) | ||
| missing = u.to(table.device) < self._missing_rate[..., None, None] | ||
| return mask_cells(table, missing) | ||
|
|
||
| def __repr__(self, *, indent: int = 0) -> str: | ||
| return f"{' ' * indent}{self.__class__.__name__}(rate={self.rate})" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import torch | ||
|
|
||
| from sdm import CategoricalTensor, TableTensor | ||
| from sdm.processing import MaskRandom | ||
|
|
||
|
|
||
| def test_masks_cells_at_the_configured_rate() -> None: | ||
| rate = 0.05 | ||
| table = TableTensor( | ||
| numerical=torch.randn(4, 4000, 3), | ||
| categorical=CategoricalTensor( | ||
| code=torch.randint(3, (4, 4000, 2)), | ||
| categories=(torch.arange(3),) * 2, | ||
| ), | ||
| ) | ||
|
|
||
| output = MaskRandom(rate=(rate, rate)).fit_transform(table) | ||
|
|
||
| numerical_missing = output.numerical.isnan() | ||
| categorical_missing = output.categorical.code == -1 | ||
| missing = torch.cat((numerical_missing, categorical_missing), dim=-1) | ||
| actual_rate = missing.float().mean(dim=(-2, -1)) | ||
| torch.testing.assert_close( | ||
| actual_rate, | ||
| torch.full_like(actual_rate, rate), | ||
| rtol=0.0, | ||
| atol=0.01, | ||
| ) | ||
| assert output.numerical[~numerical_missing].equal( | ||
| table.numerical[~numerical_missing] | ||
| ) | ||
| assert output.categorical.code[~categorical_missing].equal( | ||
| table.categorical.code[~categorical_missing] | ||
| ) | ||
| assert all( | ||
| actual.equal(expected) | ||
| for actual, expected in zip( | ||
| output.categorical.categories, | ||
| table.categorical.categories, | ||
| strict=True, | ||
| ) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: NVIDIA/structured-data-models
Length of output: 8808
🏁 Script executed:
Repository: NVIDIA/structured-data-models
Length of output: 41488
Match random draws to their generator device.
When
table.devicediffers fromgenerator.device,_fitcan fail while sampling_missing_rate._transformcan also fail when the default tensor device is CUDA because its CPU generator then produces a CUDA tensor. Sample on the generator device, move the fitted rate totable.device, and force the transform draw to CPU.🐛 Suggested fix
self._set_buffer( "_missing_rate", uniform( low=self.rate[0], high=self.rate[1], size=table.size()[:-2], - device=table.device, + device=( + table.device + if generator is None + else generator.device + ), dtype=table.numerical.dtype, generator=generator, - ), + ).to(table.device), ) def _transform(self, table: TableTensor) -> TableTensor: num_columns = table.numerical.size(-1) + table.categorical.size(-1) u = torch.rand( (*table.size()[:-1], num_columns), + device="cpu", generator=self._transform_generator(), )🤖 Prompt for AI Agents