-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
Upsample2d #414
Merged
Merged
Upsample2d #414
Changes from 10 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
f7adc6f
draft implementation of upsample2d
gboduljak ea0452c
added tests
gboduljak 4c42e25
docs
gboduljak 485fdfe
added tests for different height and with
gboduljak 3cf5943
tests for _extra_repr
gboduljak 2bced16
added upsample layer to docs
gboduljak 3611099
Update acknowledgements
gboduljak d9e5283
Merge branch 'main' into upsample-2d
gboduljak f815683
Refactor Upsample2d
angeloskath 69f0643
Fix bilinear bug and tests
angeloskath 4e586ae
Update python/mlx/nn/layers/upsample.py
gboduljak adf722f
Update python/mlx/nn/layers/upsample.py
gboduljak 8fb7ddf
Update python/mlx/nn/layers/upsample.py
gboduljak 81a5ae1
improved docs examples readability
gboduljak 57eb900
Merge branch 'upsample-2d' of github.com:gboduljak/mlx into upsample-2d
gboduljak e548f8f
removed unused import
gboduljak c0f68e8
Merge branch 'main' into upsample-2d
gboduljak cea969b
rename to Upsample
gboduljak 2980022
fix docs upsample link
gboduljak 319e2e9
renamed scale to scale_factor
gboduljak 9acad14
Merge branch 'main' into upsample-2d
gboduljak 9ec4556
updated ACKNOWLEDGMENTS.md
gboduljak 04ea7b0
added align_corners
gboduljak 621a84b
Generalize upsample to many dims
angeloskath 8e07a0a
Merge branch 'main' into upsample-2d
angeloskath 4fb92da
Change to linear and update docs
angeloskath 217905f
Fix ACKNOWLEDGMENTS
angeloskath 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 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 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 |
---|---|---|
|
@@ -35,3 +35,4 @@ Layers | |
SinusoidalPositionalEncoding | ||
Step | ||
Transformer | ||
Upsample2d |
This file contains 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 |
---|---|---|
|
@@ -64,3 +64,4 @@ | |
TransformerEncoder, | ||
TransformerEncoderLayer, | ||
) | ||
from mlx.nn.layers.upsample import Upsample2d |
This file contains 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,145 @@ | ||
# Copyright © 2023-2024 Apple Inc. | ||
|
||
from typing import List, Literal, Tuple, Union | ||
|
||
import mlx.core as mx | ||
from mlx.nn.layers.base import Module | ||
|
||
|
||
def upsample2d_nearest(x: mx.array, scale: Tuple[float, float]): | ||
# Integer scales means we can simply expand-broadcast and reshape | ||
if tuple(map(int, scale)) == scale: | ||
sh, sw = map(int, scale) | ||
B, H, W, C = x.shape | ||
x = x[:, :, None, :, None] | ||
x = mx.broadcast_to(x, (B, H, sh, W, sw, C)) | ||
x = x.reshape(B, H * sh, W * sw, C) | ||
return x | ||
|
||
# Floating point scale means we need to do indexing | ||
else: | ||
sh, sw = scale | ||
B, H, W, C = x.shape | ||
new_H = int(H * sh) | ||
new_W = int(W * sw) | ||
idx_y = (mx.arange(0, new_H) / sh).astype(mx.int32) | ||
idx_x = (mx.arange(0, new_W) / sw).astype(mx.int32) | ||
return x[:, idx_y[:, None], idx_x[None]] | ||
|
||
|
||
def upsample2d_bilinear(x: mx.array, scale: Tuple[float, float]): | ||
sh, sw = scale | ||
B, H, W, C = x.shape | ||
new_H = int(H * sh) | ||
new_W = int(W * sw) | ||
idx_y = mx.arange(0, new_H) * ((H - 1) / (new_H - 1)) | ||
idx_x = mx.arange(0, new_W) * ((W - 1) / (new_W - 1)) | ||
# Compute the sampling grid | ||
idx_y_t = mx.floor(idx_y).astype(mx.int32) | ||
idx_y_b = mx.ceil(idx_y).astype(mx.int32) | ||
idx_x_l = mx.floor(idx_x).astype(mx.int32) | ||
idx_x_r = mx.ceil(idx_x).astype(mx.int32) | ||
# Sample | ||
a = x[:, idx_y_t[:, None], idx_x_l[None]] | ||
b = x[:, idx_y_t[:, None], idx_x_r[None]] | ||
c = x[:, idx_y_b[:, None], idx_x_l[None]] | ||
d = x[:, idx_y_b[:, None], idx_x_r[None]] | ||
# Compute bilinear interpolation weights | ||
y_weight = (idx_y - idx_y_t)[:, None, None] | ||
x_weight = (idx_x - idx_x_l)[None, :, None] | ||
w_a = (1 - x_weight) * (1 - y_weight) | ||
w_b = x_weight * (1 - y_weight) | ||
w_c = y_weight * (1 - x_weight) | ||
w_d = x_weight * y_weight | ||
# Interpolate | ||
return w_a * a + w_b * b + w_c * c + w_d * d | ||
|
||
|
||
class Upsample2d(Module): | ||
r"""Upsamples the given spatial data. | ||
|
||
The input is assumed to be a 4D tensor where the channels are expected to be last. | ||
Thus, the input shape should be :math:`(N, H, W, C)` where: | ||
- ``N`` is the batch dimension | ||
- ``H`` is the input image height | ||
- ``W`` is the input image width | ||
- ``C`` is the number of input channels | ||
|
||
Parameters: | ||
scale (float or Tuple[float, float]): The multiplier for spatial size. | ||
If a single number is provided, the provided value is the | ||
multiplier for both the height and width. Otherwise, the first | ||
element of the tuple is the height multipler, while the second is | ||
the width multipler. | ||
gboduljak marked this conversation as resolved.
Show resolved
Hide resolved
|
||
mode (str, optional): The upsampling algorithm: one of ``nearest`` and | ||
``bilinear``. Default: ``nearest``. | ||
gboduljak marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Examples: | ||
>>> import mlx.core as mx | ||
>>> import mlx.nn as nn | ||
>>> x = mx.arange(1, 5).reshape((1, 2, 2, 1)) | ||
>>> x | ||
array([[[[1], | ||
[2]], | ||
[[3], | ||
[4]]]], dtype=int32) | ||
>>> n = nn.Upsample2d(scale=2, mode='nearest') | ||
>>> n(x) | ||
array([[[[1], | ||
[1], | ||
[2], | ||
[2]], | ||
[[1], | ||
[1], | ||
[2], | ||
[2]], | ||
[[3], | ||
[3], | ||
[4], | ||
[4]], | ||
[[3], | ||
[3], | ||
[4], | ||
[4]]]], dtype=int32) | ||
gboduljak marked this conversation as resolved.
Show resolved
Hide resolved
|
||
>>> b = nn.Upsample2d(scale=2, mode='bilinear') | ||
>>> b(x) | ||
array([[[[1], | ||
[1.33333], | ||
[1.66667], | ||
[2]], | ||
[[1.66667], | ||
[2], | ||
[2.33333], | ||
[2.66667]], | ||
[[2.33333], | ||
[2.66667], | ||
[3], | ||
[3.33333]], | ||
[[3], | ||
[3.33333], | ||
[3.66667], | ||
[4]]]], dtype=float32) | ||
""" | ||
|
||
def __init__( | ||
self, | ||
scale: Union[float, Tuple[float, float]], | ||
mode: Literal["nearest", "bilinear"] = "nearest", | ||
): | ||
super().__init__() | ||
if mode not in ["nearest", "bilinear"]: | ||
raise ValueError("[upsample2d] unsupported upsampling algorithm") | ||
gboduljak marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if isinstance(scale, (list, tuple)): | ||
self.scale = tuple(map(float, scale)) | ||
else: | ||
self.scale = (float(scale), float(scale)) | ||
self.mode = mode | ||
|
||
def _extra_repr(self) -> str: | ||
return f"scale={self.scale}, mode={self.mode!r}" | ||
|
||
def __call__(self, x: mx.array) -> mx.array: | ||
if self.mode == "bilinear": | ||
return upsample2d_bilinear(x, self.scale) | ||
else: | ||
return upsample2d_nearest(x, self.scale) |
This file contains 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
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.
I notice PyTorch has a single
Upsample
class which handles different dimensions. It might be worth making that consistent and then throwing (or supporting) on the dimensions not yet handled.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.
https://pytorch.org/docs/stable/generated/torch.nn.Upsample.html
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.
@awni Thank you for this suggestion. I was thinking of implementing upsampling within
nn.Upsample
. I had a similar idea/comment on #357. There, I went withnn.Pooling
instead ofnn.MaxPooling1d
ornn.MaxPooling2d
and @angeloskath suggested we go for a different class based on the dimension or pooling type. Thus, to be consistent with that review, I implementednn.Upsample2d
. In my opinion, 2D upsampling is also the most common use case.Could you please share your thoughts on whether we want
nn.Upsample2d
ornn.Upsample
, based on what we might have for pooling?