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

Fix torch backend random.categorical #389

Merged
merged 1 commit into from
Jun 22, 2023
Merged
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
3 changes: 2 additions & 1 deletion keras_core/backend/torch/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ def categorical(logits, num_samples, dtype="int32", seed=None):
logits = convert_to_tensor(logits)
dtype = to_torch_dtype(dtype)
generator = torch_seed_generator(seed, device=get_device())
probs = torch.softmax(logits, dim=-1)
return torch.multinomial(
logits,
probs,
num_samples,
replacement=True,
generator=generator,
Expand Down
5 changes: 3 additions & 2 deletions keras_core/random/random_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ def test_uniform(self, seed, shape, minval, maxval):
)
def test_categorical(self, seed, num_samples, batch_size):
np.random.seed(seed)
# Definitively favor the batch index.
logits = np.eye(batch_size) * 1e9
# Create logits that definitely favors the batch index after a softmax
# is applied. Without a softmax, this would be close to random.
logits = np.eye(batch_size) * 1e5 + 1e6
res = random.categorical(logits, num_samples, seed=seed)
# Outputs should have shape `(batch_size, num_samples)`, where each
# output index matches the batch index.
Expand Down