N-Gram in Swin Transformers for Efficient Lightweight Image Super-Resolution
Paper · 2023 · Haram Choi, Jeongmin Lee and Jihoon Yang
Summary
Enlarging a low-resolution image is easy. Recovering the texture or shape that was lost when the image became smaller is harder. A faint mark inside one region may be ambiguous on its own, while the same pattern is clearer just outside that region. The authors study this problem in Swin, a vision Transformer that controls computation by applying attention inside small windows. Shifting the windows between blocks lets information travel across their boundaries over time. The paper asks whether a block can use nearby evidence immediately, without running pixel-level attention over a much larger area.
The authors borrow the idea of an N-gram from language, where a sequence of neighboring characters or words can provide context for an individual unit. In their image version, the unit is a whole Swin window. A grouped convolution compresses each window to one feature vector. Attention slides over small neighborhoods of these vectors, looking towards the lower right and upper left, then produces a summary for each window. The network adds that summary to every position in the window before applying its usual local attention. The positions keep their individual features, while the summary gives them a shared source of evidence from nearby windows.
The paper uses this operation to pursue different goals. NGswin is designed to limit computation. Its encoder processes progressively smaller feature grids, while a bottleneck called SCDP brings features from different resolutions together for a short decoder. On Urban100 at ×4 enlargement, NGswin scores 26.45 dB in peak signal-to-noise ratio and 0.7963 in structural similarity. It uses 36.4G multiply-add operations for a 1280 × 720 output, compared with 61.7G for SwinIR-light. SwinIR-NG takes the existing SwinIR-light architecture and adds the context operation to improve reconstruction quality. At the same scale on Urban100, it reaches 26.61 dB and 0.8010, using 63.0G multiply-add operations. The authors also add the operation to HNCT, where the improvements are generally smaller.
The controlled comparisons show why the details matter. Increasing the width or depth of NGswin without adding context uses more operations and falls short of its Urban100 reconstruction scores at ×4. Supplying zeros at the boundaries of the compressed window grid can make an attention-equipped network score below the version without that attention. Reflecting neighboring window features into those boundary positions gives better results. Together, the experiments support a specific conclusion about bicubic super-resolution. Nearby windows can supply evidence that improves reconstruction, and summarizing those windows makes it possible to use that evidence without attending to every neighboring pixel separately.
Deep dive: N-Gram in Swin Transformers for Efficient Lightweight Image Super-Resolution
How NGswin uses neighboring windows to recover image detail with fewer operations, and what changes when the same method is added to SwinIR. · about 36 minutes to read
The problem and its context
Why a window boundary can matter in reconstruction
Single-image super-resolution starts with a low-resolution input and produces a high-resolution estimate of the same image. The benchmark setup begins with a known high-resolution image and reduces it to create the input. The reconstruction can then be checked against the original. The missing information is the reason to learn a reconstruction procedure in the first place. A low-resolution patch may retain enough evidence to locate a broad edge while leaving the exact arrangement of finer lines uncertain.
The paper treats this uncertainty as a problem of access to context. An image can repeat a structure over neighboring regions. If several pieces of a pattern survive the reduction to low resolution, they can help resolve an ambiguous piece. Whether the reconstruction system can use them depends on which feature positions are allowed to influence one another, and when. A boundary introduced for computation can cut through a feature that is visually continuous across that boundary.
Window self-attention, abbreviated WSA, makes this tradeoff especially visible. In Swin, the feature grid is divided into disjoint windows for a local attention operation. A position can assign weights to other positions in its current window and gather their information. A position outside that window contributes no direct evidence to that operation. Limiting the comparisons this way avoids the cost of constructing an attention map with all possible pairs across the entire feature grid.
Swin's shifted windows already provide a route across the original boundaries. A subsequent block offsets the window partition, so positions that were in different windows may now be processed together. Repeated blocks can therefore communicate over a larger area than the window of any individual block. This is compatible with the authors' criticism of plain WSA. The question is whether information arrives in a form and at a depth that helps recover a specific texture. A sequence of local exchanges offers a different route from giving the current block a summary of nearby windows before its own attention takes place.
To illustrate the problem, the authors inspect feature maps after attention in shallow and deeper blocks. In the shallow layers without their context operation, adjacent regions can have visibly different feature responses aligned with the window partition. Deeper layers make that division less apparent, but in the example the target region still has a response that differs from nearby regions with related patterns. The associated reconstruction contains a distortion. With their context operation, the authors show related regions taking on more similar responses and a better reconstruction in the illustrated area. These feature maps motivate the design. They show how the authors diagnosed particular examples, while the test scores and controlled comparisons address how frequently the intervention helps across benchmark images.
How earlier work managed the cost
The efficient super-resolution systems the authors discuss reduce cost in different parts of the network. CARN uses a cascade of residual blocks, giving later parts of the network access to earlier representations. IMDN combines information distillation with selective feature fusion. LatticeNet is organized around a lattice filter. SRPN-Lite uses pruning on EDSR-baseline, a convolutional super-resolution system. The general design problem predates Swin. A method has to decide which information to retain and how much computation to spend transforming it before generating the larger image.
The paper also describes approaches that combine convolution and attention. ESRT uses convolution alongside a Transformer that reduces the channel dimension. SwinIR-light and HNCT combine convolution with Swin blocks. ELAN-light divides features into groups for multiscale self-attention. These choices matter to the paper's comparisons because a small parameter count can coexist with a substantial arithmetic bill. Applying the same learned operation at many spatial positions reuses its parameters while still doing work at each of those positions. The authors consequently track both learned parameter count and multiply-add operations, which they abbreviate as Mult-Adds.
Swin itself comes in versions that make different choices about attention and normalization. The original uses scaled dot products and places normalization before the transformations in its residual branches. Swin V2 uses scaled cosine similarity and residual post-normalization. Both retain window-based processing. NGswin adopts the latter version's attention and normalization conventions. When the paper adds its context operation to SwinIR-light and HNCT, it retains the scaled dot-product attention of those designs. This provides a way to ask whether the neighborhood operation is useful beyond the particular Swin version used in NGswin.
What transfers from text
A textual n-gram takes a sequence of neighboring units, such as characters or words. The paper discusses statistical uses of these groups and neural approaches that represent them by averaging embeddings, recurrent computation or attention. It also distinguishes a group from the representation of the individual units within it. In the image method, the individual unit already has internal structure. A Swin window contains multiple feature positions, and those positions can interact with one another. The neighborhood operation works at a higher level of grouping, where each whole window contributes one embedding.
As the authors describe earlier visual uses of n-grams, Pixel N-grams groups individual pixels along a horizontal or vertical direction. View N-gram Network groups successive views of an object. The units in NGswin are spatial windows taken from a single image. The neighborhood occupies an area on the window grid, so extending towards the lower right means including a block of windows anchored at the target, with room for neighbors along both spatial axes. The text analogy supplies the idea of grouping nearby units. The image layout determines what counts as nearby and how many directions are available.
This choice puts two kinds of spatial reasoning inside a block. Window-level processing asks which surrounding summaries can inform the target window. Position-level processing then asks what the individual features in that window imply about its reconstruction. Keeping the two operations distinct gives the authors room to reduce the cost of the first without reducing the number of feature positions available to the second.
The method, step by step
From the input image to a reconstruction
NGswin preserves the input image's spatial resolution at the start. A convolution turns the input into a grid of feature vectors. The encoder processes that grid and then works at progressively coarser resolutions. At each stage, its blocks can gather context from surrounding windows. After encoding, a bottleneck collects the stage outputs, aligns them at the input resolution and combines them. A short decoder refines the combined representation. The reconstruction module is where the grid grows to the requested output size.
How NGswin reconstructs a high-resolution image
The steps in order.
The overall structure follows the encoder, bottleneck and decoder arrangement of U-Net. The asymmetry is deliberate. Much of the processing takes place in the encoder, where later stages can run on smaller grids. The decoder operates at the input image's resolution and has a single stage. The architecture therefore needs a way to bring back information from the finer encoder grid before decoding. The SCDP bottleneck handles that transfer, while skip connections preserve shorter routes from early feature maps to later ones.
Encoding at several resolutions
The input, denoted Iᴸᴿ, has 3 color channels, height H and width W. A 3 × 3 convolution extracts the shallow feature map zₛ. This map can be written as HW rows with D features in each row. H and W still describe the input grid even when the spatial positions are written as a single list. D is the number of channels in the internal representation. The authors set D to 64.
The encoder has three stages. Each contains a stack of N-Gram Swin Transformer Blocks, abbreviated NSTBs. The default stage depths are {6, 4, 4}. The following recurrence expresses what a block does to the features supplied by the preceding block in the same stage.
zₑₙ꜀[i,k] = Fₑₙ꜀i,k
Here zₑₙ꜀[i,k] is the encoder output after block k in stage i, and Fₑₙ꜀[i,k] is the transformation performed by that block. The input zₑₙ꜀[i,k−1] is the feature map before the transformation. The first block in a stage has k equal to 1, so index 0 denotes the stage input. The number of blocks in stage i is Kᵢ. At the first stage, the block stack starts from the shallow features. At later stages, it operates on features passed down from the preceding resolution, with pooled features from earlier parts of the encoder also routed across stages.
zₑₙ꜀[i,k] ∈ ℝ^(hw × D)
In this shape expression, zₑₙ꜀[i,k] is the output just defined, ℝ denotes real-valued arrays, h and w are the height and width at stage i, and hw is the number of spatial positions. D remains the channel dimension. The multiplication sign in the shape separates the position and channel axes.
(h, w) = (H / 2^(i−1), W / 2^(i−1))
The ordered pair on the left gives the stage height h and width w. H and W on the right are the input height and width. The stage index i determines how many times the grid has been halved along each axis. The first stage works at input resolution. Patch merging after that stage and after the next stage accounts for the reductions in the expression.
Patch merging collects features from each 2 × 2 group of spatial positions and projects the resulting 4D channels down to D. The paper contrasts this with Swin's usual projection to 2D. Keeping the width at D makes the spatial reduction do more of the work of controlling computation. At the training crop size, the default encoder stages operate on 64 × 64, 32 × 32 and 16 × 16 grids. A block deeper in the encoder still uses the configured local window size, but a position on that grid represents features after more spatial aggregation.
The encoder also routes earlier features forward by pooling and concatenating them across stages. Max pooling is applied where necessary to bring an earlier feature map to the resolution of the stage that receives it. This is the paper's adaptation of CARN's global cascade. It gives features and gradients additional routes across the network. Within a stage, the paper uses residual connections, which carry information by addition along the sequence of blocks and into patch merging where it is present. The within-stage and across-stage connections serve different purposes and use different ways of joining signals.
Compressing a local window into a uni-gram
The context operation begins with the entire feature grid entering a block. Think of its regular window partition as a second, coarser grid. Each cell on this coarser grid represents a whole local window, which the authors call a uni-gram. Within the original grid, the window has M positions along each side. The default for M is 8. The uni-gram embedding summarizes the entire window in a single vector with half the channel width of the original features.
zᵤₙᵢ ∈ ℝ^(D/2 × wₕ × w𝓌)
Here zᵤₙᵢ is the grid of uni-gram embeddings and ℝ denotes real-valued arrays. D is the feature width of the block input. The D/2 axis contains the reduced channels, wₕ counts windows along the height, and w𝓌 counts windows along the width. The multiplication signs separate the axes of the array.
(wₕ, w𝓌) = (h / M, w / M)
The pair wₕ and w𝓌 gives the number of local windows along each axis. The feature map has height h and width w at the current stage. M is the side length of a local window. This formula describes the grid when the features are divided into windows of that size.
A grouped convolution performs the summarization. Its kernel is M × M and its stride is M, so each application covers one distinct window. The convolution has D/2 groups. Grouping limits which input channels are used together in a convolutional output. The reduction in spatial positions is particularly important here. The next attention operation sees one vector per window and a narrower channel axis, so it can compare surrounding windows without building pixel-to-pixel interactions across the whole neighborhood.
The paper uses the following Swin attention cost expression to explain the value of those reductions.
Ω(WSA) = 4hwD² + 2M²hwD
Ω(WSA) denotes the arithmetic complexity of window self-attention over a feature map with height h, width w and D channels. M is the window side length. The term 4hwD² accounts for the linear projections, and 2M²hwD accounts for attention score and value operations within windows. The position count hw enters both terms. Channel width enters quadratically in the projection term and linearly in the second term. The expression describes ordinary window attention and shows why reducing position count and channel width helps before adding a separate sliding operation. The paper reports the cost of the assembled networks in its experimental comparisons.
Sliding attention over the window grid
The next step builds a context for each target window. With N set to 2 in the default configuration, the forward neighborhood occupies an N × N block of uni-gram embeddings extending to the lower right from the target. It covers the target window, its neighbor along each of the two axes in that direction, and the diagonal neighbor. The backward pass uses the corresponding upper-left block. The authors use forward and backward as names for these orientations on an image grid.
For each placement of the neighborhood, the network computes self-attention among the uni-gram vectors. It then averages the resulting vectors across that neighborhood. As the neighborhood moves across the coarser grid, each target window receives one pooled forward vector and one pooled backward vector. Consecutive placements can have overlapping inputs. The attention and pooling for a placement produce its own summary, with weights shared across placements and between the forward and backward passes. The neighborhood embeddings themselves come from the same feature grid in both passes.
This sequence gives the procedure the spatial organization of a sliding convolution. Its choice of which features to emphasize is supplied by attention. The correlation weights depend on the neighborhood features being processed. Pooling then produces a vector at each anchor position, ready to be added to the target window. To transfer the idea to SwinIR-light and HNCT, the authors preserve this arrangement of compression, sliding interaction and pooling, and use the scaled dot-product attention that those systems already employ.
For NGswin, the attention rule comes from Swin V2. The following formula describes it for a local window. The sliding operation uses the same rule with the side length N and the narrowed embedding width.
WSA(Q, K, V) = Softmax(cos(Q, K) / τ + B) V
WSA is window self-attention. Q is the query matrix, K the key matrix and V the value matrix. A row represents the projected feature of one position in the window. Queries describe what each position is looking for, keys describe the features against which it is compared, and values are the features combined in the result. The function cos(Q, K) gives a matrix of cosine similarities for all query and key pairs in the window. The learned scalar τ controls their scale before softmax, and is constrained to be larger than 0.01. B is a learned relative position bias matrix. It adds a score for the position of one feature relative to another before Softmax converts the scores for each query into weights. Multiplying by V takes the weighted combination of value vectors.
In the paper's notation for an ordinary window, Q, K and V each have M² rows and D channels, and B has M² rows and M² columns. For attention on the compressed neighborhoods, there are N² positions in a neighborhood, with channel width D/2. For clarity, the cosine calculation can be written for a single entry of the similarity matrix.
cos(Q, K)[a,b] = (qₐ / ‖qₐ‖₂) · (kᵦ / ‖kᵦ‖₂)
The indices a and b identify the query and key positions. The vector qₐ is row a of Q and kᵦ is row b of K. The double bars with subscript 2 denote the Euclidean length of the enclosed vector. Dividing by those lengths makes the dot product, marked by ·, depend on the directions of the vectors. The expression on the left is the entry at row a and column b of the pairwise cosine matrix. The learned scale and the relative position bias are applied after this comparison, as in the attention formula.
Supplying context at the edges
A target near the bottom or right edge cannot obtain its full forward neighborhood from actual windows in that direction. The same issue arises for the backward neighborhood at the top or left edge. The procedure pads the uni-gram grid by N − 1 window positions on the relevant sides. Here N is the side length of the sliding neighborhood, so the padding is measured on the grid of window embeddings. It takes place after the convolution that created that grid.
The authors populate the padding by reflecting existing embeddings in sequence beyond the edge. For forward context, the padding goes at the lower and right edges, using rows and columns just inside that boundary. For backward context, the operation is reversed at the upper and left edges. A neighborhood that would otherwise extend outside the grid can thus be formed using features drawn from the image. The reflected entries stand in for unavailable neighbors and do not supply additional observations outside the original image.
The paper's padding example uses N equal to 2 and shows how a forward neighborhood at the edge can include the embedding reflected from the next window inward. This detail becomes more consequential at deeper stages, where the window-embedding grid has few entries. With the training crop sizes and the default window, the stages work with uni-gram grids of 8 × 8, 4 × 4 and 2 × 2. Padding can account for a consequential share of the context seen by edge windows in such grids. The authors keep the padded array size the same as for zero padding, so the subsequent attention has the same arithmetic count.
Returning context to individual positions
After the sliding passes, the forward and backward vectors at each window location are concatenated. A 1 × 1 convolution maps that concatenated representation to the D channels of the original block input. This gives one context vector per window. The same vector is added to every feature position in that particular window. The operation matches channels and window location, with each position retaining its own original feature values.
The addition happens before the regular Swin attention in the block. When the block computes its queries, keys and values, they are therefore functions of both the individual position features and the shared window context. This is how information from neighboring windows affects the attention that operates on the more detailed grid. The context vector is also distinct from the relative position bias B. The vector changes the input features; B adds position-dependent terms to the attention scores later.
Even-numbered blocks apply Swin's window shift. With the default window size of 8, the shift size is 4. The context operation supplements this schedule. Regular and shifted windows still let information move between positions across blocks. The sliding N-gram path explicitly supplies neighboring-window information within a block. After window attention, the block includes a feed-forward network with hidden width 128 and GELU activation. The authors use post-normalization and set the number of attention heads by stage to {6, 4, 4, 6}, counting the decoder as the final stage. This head configuration applies to both the sliding and the regular attention.
Fusing the stages before decoding
The encoder's coarsest output has seen broader spatial structure after patch merging, but the finest grid contains detail closer to what the reconstruction needs. The SCDP bottleneck uses both kinds of representation. Its name comes from pixel shuffle, concatenation, depthwise convolution and pointwise projection. The inputs are the final block outputs from the encoder stages, together with the shallow features used to supplement those outputs.
For each stage, the shallow features are brought to the corresponding spatial resolution by iterative 2 × 2 max pooling as needed. The bottleneck algorithm includes a LeakyReLU activation in this downsampling path. The resulting shallow representation is added to the stage's final block output. The stage contributions are then brought to the original input height and width by pixel shuffle. Pixel shuffle takes values stored in channels and rearranges them into positions on a larger spatial grid. Unlike the final output upsampling, this shuffle makes intermediate representations align at the resolution of the low-resolution input.
Once aligned, the stage features are concatenated along the channel axis. A 3 × 3 depthwise convolution learns spatial transformations separately within the channels. GELU follows that convolution. A pointwise projection then mixes channels at each position to bring the width back to D. This sequence allows the bottleneck to apply spatial processing to the combined features without using a full convolution that mixes all channels at every spatial offset. The algorithm finishes with layer normalization. Layer Normalization
The decoder begins by adding the first encoder stage's final output to the bottleneck features. The two arrays already have matching spatial dimensions. This skip connection gives the decoder a direct route to the encoder representation at the finest stage resolution. The decoder applies a sequence of NSTBs, following the same block design as the encoder, and then normalizes the final output.
z_dₑ꜀[0] = zₛ꜀dₚ + zₑₙ꜀[1,K₁]
Here z_dₑ꜀[0] is the input to the decoder's first block. The term zₛ꜀dₚ is the SCDP output, and zₑₙ꜀[1,K₁] is the output at the last block of encoder stage 1. K₁ is that stage's block count. The plus sign denotes elementwise addition of feature maps at the low-resolution input height and width, each with D channels.
z_dₑ꜀[k] = F_dₑ꜀k
The feature map z_dₑ꜀[k] is the output of decoder block k. Its input is z_dₑ꜀[k−1], and F_dₑ꜀[k] is the transformation implemented by that block. The index k runs from 1 to K_dₑ꜀. The default decoder depth K_dₑ꜀ is 6. The block outputs have HW positions and D channels.
z_dₑ꜀ = LayerNorm(z_dₑ꜀[K_dₑ꜀])
The quantity z_dₑ꜀ is the normalized decoder result. LayerNorm applies layer normalization to the last block output, which is indexed by K_dₑ꜀, the number of decoder blocks. The operation preserves the shape of the feature map. After it, a global skip connection adds the shallow feature map zₛ to z_dₑ꜀. This gives the reconstruction stage both the result of the longer encoding and decoding path and features taken directly from the first convolution.
Producing the larger image
The reconstruction module begins with a convolution that expands the channel count to prepare for pixel shuffle. In the appendix, the authors diagram how the necessary number of channels changes with the desired enlargement.
D → r² × 3 → 3
D is the incoming channel count, r is the enlargement factor along each spatial axis, and 3 is the output color channel count. The first arrow is the channel change performed by the convolution. The second arrow is the channel change at pixel shuffle, which moves the other values into the expanded spatial axes. The paper illustrates this arrangement for r equal to 2, 3 and 4. A final convolution maps the resulting color channels to the reconstructed image.
Iˢᴿ ∈ ℝ^(3 × rH × rW)
Iˢᴿ is the super-resolved output image and ℝ denotes real-valued arrays. The first axis has 3 color channels. H and W are the low-resolution input height and width, and r multiplies each to give the output height and width. The architecture can therefore keep the encoder, bottleneck and decoder design fixed when switching tasks, with the reconstruction head supplying the scale-specific transformation.
The authors also give an approximate relationship between the resolution at which an NSTB operates and its arithmetic cost for a scale task.
MultAdds(NSTB) ≈ (10 × hw / 2¹² / (r / 2)²) G
MultAdds(NSTB) denotes the approximate cost of one N-Gram Swin Transformer Block, and ≈ indicates an estimate. The product hw is the number of positions at that block's training input resolution, and r is the super-resolution scale factor. The constants 10, 2 and 12 are the ones in the paper's approximation; G denotes billions of multiply-add operations. The expression is used to illustrate the effect of spatial resolution, not to replace the reported counts for the complete network. The authors estimate that keeping the blocks of the second and third encoder stages at full input resolution would add about 17G operations on the ×4 task.
Preparing the examples and training the networks
The main training data consist of 800 high-resolution and low-resolution image pairs from DIV2K. The low-resolution images are produced with the MATLAB bicubic kernel at the appropriate scale. During training, the authors sample 64 × 64 crops on the low-resolution side and use corresponding high-resolution targets. They augment the examples with random horizontal flips and rotations of 90°, 180° and 270°. The appendix says that each training image is repeated 80 times within an epoch so that random cropping can expose different regions. Images, including those used for testing, are stored in NumPy files with the uint8 data type.
Training minimizes absolute pixel error between the reconstructed image and its matching target.
L = ‖Iᴴᴿ − Iˢᴿ‖₁
L is the training loss. Iᴴᴿ denotes the high-resolution reference, and Iˢᴿ is the network's reconstruction for the corresponding input. The difference is taken at corresponding pixel and color positions. The bars with subscript 1 denote the L1 norm of that difference, which penalizes the magnitudes of the pixel errors. The test metrics address related questions about fidelity, but the loss shown here is the one the authors optimize.
For NGswin, the training inputs are normalized using channel means and standard deviations computed from the 800 low-resolution training images for each scale. The normalization is over the RGB channels. The output is transformed back to the original scale before the loss is evaluated. SwinIR-NG follows SwinIR's convention of using 1.0 for the standard deviation. This is one reason the published recipes should be read with the architecture names attached. The context operation transfers across backbones, while some of the training details follow the existing backbone.
According to the report, the implementation runs on four NVIDIA TITAN Xp GPUs and uses PyTorch. The batch size is 64. The scratch schedule runs for 500 epochs. The authors give Adam settings of 0.9 and 0.999 for the coefficients of the running gradient estimates and 10⁻⁸ for the numerical constant. They report an initial learning rate of 0.0004 for the main schedule and halve it after epochs {200, 300, 400, 425, 450, 475}. The startup warmup is listed as 20 epochs. The appendix gives its target separately as 10⁻⁴, which differs from the stated initial rate.
For NGswin and SwinIR-NG, ×2 is trained from scratch. For ×3 and ×4 the authors load the learned ×2 weights and initially train only the reconstruction module for the new scale. That phase lasts 50 epochs at a constant learning rate of 0.0004. They then adjust the entire network with AdamW for 250 epochs. This second phase has 10 warmup epochs and halves the learning rate after epochs {50, 100, 150, 175, 200, 225}. The paper refers to the resulting 300-epoch procedure as warm-start training. HNCT-NG is trained from scratch at all scales. The authors release their implementation under the project name NGramSwin.
Experiments and results
What the evaluation measures
The test sets are Set5, Set14, BSD100, Urban100 and Manga109. Each test starts from a low-resolution image created from its high-resolution counterpart with the MATLAB bicubic kernel for the chosen scale. The reconstruction is then evaluated against that counterpart. The ×2, ×3 and ×4 results belong to distinct enlargement tasks. Even when the high-resolution test image is the same, the network starts with a differently sized input and a different amount of available spatial detail.
The paper reports peak signal-to-noise ratio, or PSNR, in dB. Higher PSNR corresponds to smaller squared reconstruction error relative to the image signal's peak. The other score, structural similarity or SSIM, assesses agreement in image structure and appearance. Higher SSIM also indicates better agreement. Both are evaluated on Y, the luminance component of the YCbCr color representation. This concentrates the reported comparison on brightness and spatial structure. The networks still produce color images, while the tabulated fidelity measures pertain to this one channel.
For efficiency, the papers' networks are compared by learned parameter count and Mult-Adds. The latter is reported for a 1280 × 720 high-resolution output. The specified size is important because operations over feature grids depend on image dimensions. It also explains why a network can have a larger parameter count for a larger enlargement factor while incurring fewer operations at that factor. For the stipulated output size, a greater enlargement factor starts from a smaller low-resolution grid. The scale-specific reconstruction heads can increase parameter count at the same time that much of the earlier processing takes place on fewer positions.
NGswin and the efficient systems
The efficient super-resolution comparison includes convolutional baselines such as EDSR-baseline and CARN, feature-distillation approaches such as IMDN and RFDN-L, and more recent alternatives such as HNCT, FMEN and SRPN-Lite. Training sources vary across the table. The D2K label means DIV2K. The authors identify DF2K as a combination of DIV2K and Flickr2K, with 800 + 2,650 high-resolution and low-resolution pairs. Some baseline rows involve a separate image collection. The table therefore records the data sources alongside the scores and computational measures. The authors also take the LatticeNet results from another study they cite.
On Urban100, NGswin posts 32.53 dB and 0.9324 at ×2, compared with 32.41 dB and 0.9311 for FMEN. At ×3 it reaches 28.52 dB and 0.8603, while FMEN reaches 28.33 dB and 0.8562. At ×4, NGswin scores 26.45 dB and 0.7963, with FMEN at 26.28 dB and 0.7908. NGswin is trained on D2K and FMEN on DF2K in these reported comparisons. The numbers establish how the published systems compare under those training configurations. They leave the effect of changing the training data within either architecture to a separate experiment.
The tests on other images provide useful checks on the scope of the comparison. At ×4 on Set14, NGswin attains 28.78 dB and 0.7859. HNCT posts 28.71 dB and 0.7834 there, at a lower operation count. On ×4 BSD100, NGswin reaches 27.66 dB and 0.7396. On ×4 Manga109 it reaches 30.80 dB and 0.9128, while HNCT and FMEN both record 30.70 dB, with SSIM of 0.9112 and 0.9107 respectively. The Urban100 and Manga109 comparisons figure prominently in the paper because the authors see them as demanding tests of reconstruction from DIV2K training.
Several individual scores qualify any broad claim of winning every comparison. At ×2 on Set5, NGswin's 38.05 dB is below FMEN's 38.10 dB, while its 0.9610 SSIM is above FMEN's 0.9609. At ×2 on Manga109, NGswin has 38.97 dB and 0.9777, while FMEN has 38.95 dB and 0.9778. The PSNR and SSIM rankings in these cases favor different entries. The authors report PSNR advantages of up to 0.3 dB over SRPN-Lite and 0.19 dB over FMEN across their efficient-system comparison. Those margins summarize favorable cases, while the individual rows show where they apply.
NGswin's efficiency claim is clearest against the lightweight attention systems in the paper's separate arithmetic comparison. It uses 140.4G Mult-Adds at ×2, 66.6G at ×3 and 36.4G at ×4 for the specified output. SwinIR-light uses 243.7G, 109.5G and 61.7G in the corresponding tasks. The authors say that they correct an earlier SwinIR-light arithmetic count based on a 1024×720 image. The following comparison keeps the output size and enlargement factor fixed.
Multiply-add operations for ×4 reconstruction at 1280 × 720
NGswin uses the fewest operations among the systems in this comparison.
The numbers
| System or setting | G Mult-Adds |
|---|---|
| ESRT | 67.7 |
| SwinIR-light | 61.7 |
| DiVANet | 57.0 |
| ELAN-light | 43.2 |
| NGswin (this paper) | 36.4 |
The closest comparison depends on what is being optimized. NGswin has 998K parameters at ×2, 1,007K at ×3 and 1,019K at ×4. In the efficient-system table, HNCT is smaller and uses fewer operations at all of those scales. On ×4 it has 373K parameters and 22.0G Mult-Adds. SRPN-Lite also has a lower ×4 arithmetic count than NGswin, at 35.8G. The chart depicts the systems in its own comparison group. Across the broader experiment, NGswin occupies a region where it retains competitive fidelity at a moderate operation count, with other options available for a stricter size or arithmetic budget.
SwinIR-NG and the quality-focused comparison
The second experiment asks what adding the context operation can achieve while keeping the SwinIR-light architecture as its base. The competitors include SwinIR-light, ESRT, ELAN-light and DiVANet. The main entries in this comparison are trained on DIV2K. The full-width SwinIR-NG uses 1,181K parameters and 274.1G Mult-Adds at ×2. SwinIR-light uses 910K parameters and 243.7G Mult-Adds at that scale. The extra cost is part of the trade the authors make for higher scores.
At ×2 on Urban100, SwinIR-NG reaches 32.78 dB and 0.9340. SwinIR-light has 32.76 dB and 0.9340, and ELAN-light has the same pair as SwinIR-light. On ×2 Manga109, SwinIR-NG records 39.20 dB and 0.9781, while SwinIR-light records 39.12 dB and 0.9783. The gain is clearer in some of the harder scale and dataset combinations. On ×3 Manga109, SwinIR-NG reaches 34.22 dB and 0.9488. SwinIR-light scores 33.98 dB and 0.9478, and ELAN-light scores 34.00 dB and 0.9478. The paper reports an improvement of up to 0.24 dB over the backbone without the context addition.
At ×4 on Urban100, full-width SwinIR-NG records 26.61 dB and 0.8010. ELAN-light reaches 26.54 dB and 0.7982, and SwinIR-light scores 26.47 dB and 0.7980. The comparison on ×4 Manga109 also favors the full-width design over the DIV2K-trained baselines in both measures. It reaches 31.09 dB and 0.9161, where SwinIR-light scores 30.92 dB and 0.9151. The ×4 full-width design uses 63.0G Mult-Adds and 1,201K parameters. ELAN-light's ×4 entry uses 43.2G and 601K parameters. These are quality gains accompanied by a higher resource requirement.
Urban100 test PSNR for DIV2K-trained systems at ×4
SwinIR-NG has the highest PSNR in this comparison.
The numbers
| System or setting | dB |
|---|---|
| ESRT | 26.39 |
| DiVANet | 26.42 |
| SwinIR-light | 26.47 |
| ELAN-light | 26.54 |
| SwinIR-NG (this paper) | 26.61 |
The authors also reduce SwinIR-NG's width from 60 channels to 48. The resulting ×4 system has 770K parameters and uses 42.5G Mult-Adds. On Urban100, the reduced configuration trained on DIV2K reaches 26.47 dB and 0.7977. This is the same PSNR as SwinIR-light with fewer operations, while SSIM is slightly lower. On Manga109 it gets 30.97 dB and 0.9147, compared with SwinIR-light's 30.92 dB and 0.9151. The results again depend on which fidelity measure matters and how tight the computation budget is.
Training the reduced version on DF2K keeps the same architecture and arithmetic count, while changing its scores. It reaches 26.54 dB and 0.7998 on ×4 Urban100. On ×4 Manga109 its PSNR is 31.12 dB and its SSIM is 0.9158. The latter comparison illustrates why the article distinguishes the full-width headline entry from the best score in any row. The wider DIV2K-trained version has higher SSIM there, and the reduced version trained with more data has higher PSNR. The authors also correct SwinIR-light's parameter accounting to include relative position bias tables, so the size figures in this comparison use their revised count.
The paper complements its numerical comparisons with visual reconstructions. The figures pair the bicubic input and the original high-resolution image with outputs from competing systems. The appendix includes ×4 examples from Set14 and BSD100 and examples at ×3 or ×4 from Urban100 and Manga109. It also shows paired outputs with and without the context operation. These figures let the reader inspect how changes in the scores correspond to particular lines, textures and local structures. The benchmark scores provide the aggregate comparison, while the figures show what selective improvements look like in individual regions.
What the ablations show
Adding context versus adding capacity
The most direct comparison removes the N-gram operation from NGswin while leaving the overall architecture in place. At ×2 on Urban100, the system goes from 32.39 dB and 0.9304 without context to 32.53 dB and 0.9324 with it. The respective costs are 138.20G and 140.41G Mult-Adds. At ×3 on the same set, the scores go from 28.37 dB and 0.8573 to 28.52 dB and 0.8603. These comparisons show an improvement in the tested configuration at a modest additional arithmetic cost. They also add parameters, so the authors examine whether spending capacity in a different way can reproduce the effect.
For ×4 they widen or deepen the version without N-gram context. On Urban100 the wider version reaches 26.28 dB and 0.7927 using 53.71G Mult-Adds, and the deeper version reaches 26.37 dB and 0.7946 using 47.88G. The context-equipped version reaches 26.45 dB and 0.7963 using 36.44G. The wider and deeper versions also have more parameters, at 1,189K and 1,061K, compared with 1,019K for the context version. In this part of the experiment, where the extra capacity goes matters more than simply enlarging the network.
The same rows show why the conclusion should be tied to the benchmark and metric. On ×4 Set5, the deeper version without context reaches 32.40 dB and 0.8967, while the context version has 32.33 dB and 0.8963. On ×4 Manga109, the deeper version reports 30.78 dB and 0.9133, while the context version has 30.80 dB and 0.9128. The gain in PSNR on Manga109 comes with a lower SSIM than in that deeper comparison. The N-gram operation gives a favorable quality and computation tradeoff on several benchmarks, especially Urban100. The complete rows give a more precise account of that tradeoff than a tally of wins would.
HNCT offers a test of whether the operation helps when attached to a different architecture. For Urban100 at ×3, HNCT moves from 28.28 dB and 0.8557 to 28.38 dB and 0.8573 with context. The arithmetic count rises from 37.78G to 38.14G. On ×3 Manga109 its PSNR stays at 33.81 dB and SSIM rises from 0.9459 to 0.9464. On ×2 Set14 there is a small decrease in PSNR, from 33.65 dB to 33.64 dB, alongside an increase in SSIM from 0.9182 to 0.9195. The authors suggest the generally smaller gains reflect how many layers can use the addition. HNCT has 8 Swin layers, whereas NGswin has 20. The experiment demonstrates the smaller gains in HNCT, while the explanation about layer count remains an interpretation of the comparison.
Choosing where and how to look
The context neighborhoods can extend in one direction, in the default pair of directions, or in all four diagonal orientations discussed by the authors. The paper also compares sliding attention with convolution after the uni-gram embedding. The convolution variant uses learned filters for the local interaction. The attention variant computes correlations between embeddings in each candidate neighborhood. Both can gather spatial information, so evaluating them asks whether feature-dependent weighting is worth the cost within this design.
Changing directions also changes the use of channels. The one-direction variant keeps the full channel width at the embedding step. The four-direction setup assigns D/4 channels to each directional contribution and merges the resulting features. The comparison therefore measures complete implementations with different ways of allocating capacity. It shows what happens to quality and cost when the authors build each configuration, with direction count and embedding width changing together in some rows.
On ×2 Urban100, the default two-direction attention scores 32.53 dB and 0.9324 at 140.41G Mult-Adds. Two-direction convolution gives 32.54 dB and 0.9321 at 139.38G. One-direction attention also reaches 32.54 dB, with 0.9322 SSIM and 152.41G Mult-Adds. Four-direction attention uses 139.56G and reaches 32.52 dB and 0.9317. The default is therefore a choice across several measures. It has the highest Urban100 SSIM among those rows, while a convolution variant achieves slightly higher PSNR with fewer operations.
On ×2 Manga109 the default reaches 38.97 dB and 0.9777. The four-direction convolution reaches 38.93 dB and 0.9777 using 139.17G Mult-Adds. On ×2 Set14, the two-direction convolution records 33.83 dB and 0.9203, above the default's 33.79 dB and 0.9199. These examples give substance to the authors' conclusion that the pair of directions with attention is their preferred overall tradeoff. The experiment neither orders all variants identically across test sets nor establishes that more directions always help. It supports the choice of a particular configuration for this architecture and set of objectives.
Trading spatial resolution for operations
The architecture study redistributes the same total of 20 NSTBs across different stages. The more hierarchical variant adds an encoder stage operating on 8 × 8 training features and adds a decoder stage. Its encoder and decoder spend fewer blocks at the input resolution than the default. This lowers arithmetic costs substantially while keeping parameter counts close. It also pushes more intermediate processing onto grids with less spatial detail.
The authors compare the more hierarchical version without SCDP to the default stage allocation without SCDP. In both of these cases the simpler bottleneck applies depthwise and pointwise operations to the last encoder output. On ×4 Urban100, the extra-stage configuration scores 26.22 dB and 0.7900 at 23.33G Mult-Adds. The default stage allocation without SCDP scores 26.38 dB and 0.7954 at 36.06G. On ×4 Manga109 the corresponding scores are 30.46 dB and 0.9090 for the extra stages and 30.71 dB and 0.9121 for the default allocation. The block budget alone does not determine the comparison. Spatial resolution affects both the amount of arithmetic and the detail available for reconstruction.
Adding SCDP to the default stage allocation improves ×4 Urban100 to 26.45 dB and 0.7963 at 36.44G Mult-Adds. On ×4 Manga109 it improves the scores to 30.80 dB and 0.9128. At ×3, Manga109 likewise moves from 33.81 dB and 0.9464 to 33.89 dB and 0.9470. At ×2 on Set5, the SCDP comparison runs differently. PSNR goes from 38.08 dB to 38.05 dB while SSIM goes from 0.9609 to 0.9610. The clearest evidence for multiscale fusion is in the larger gains on the harder examples. The reported rows enable a comparison with and without fusion at the default allocation. They do not include the extra-stage configuration fitted with SCDP.
The authors also examine the asymmetric decoder as a computational design choice. Their comparison of decoder sizes uses the ×2 task with a 1280×720 image. Shortening the full-input-resolution end of the network makes sense in light of the stage experiment. Operations spent on large grids are costly, so carrying early representations forward can preserve access to detail without putting the entire block budget at that resolution.
Boundary conditions and the Swin block
The padding ablation keeps the number of learned parameters and the arithmetic count fixed. One version pads with zeros; the other pads using the reflected window features. On ×2 Urban100, the zero-padded version reaches 31.58 dB and 0.9231, while reflection reaches 32.53 dB and 0.9324. The same dataset at ×4 shows 25.72 dB and 0.7740 with zeros and 26.45 dB and 0.7963 with reflection. On ×4 Manga109 the zero-padding result is 29.89 dB and 0.9016, and the reflected-padding result is 30.80 dB and 0.9128.
The zero-padding row is especially informative alongside the no-context control. NGswin without the context operation scores 26.25 dB and 0.7918 on ×4 Urban100, above the zero-padded context configuration there. Extending the computation beyond a window can therefore hurt when the extra positions supply poor inputs. The authors attribute the effect to empty features taking part in attention and pooling, which is particularly consequential on the small window grids at deeper stages. The experiment tests the choice of padding scheme as a whole; the reported numbers do not separate the effect by individual layer or boundary location.
The Swin-version ablation keeps the headline arithmetic count the same within each scale and compares NGswin using the V1 and V2 blocks. On ×2 Urban100, V1 gives 32.28 dB and 0.9301, while V2 gives 32.53 dB and 0.9324. On ×3 Manga109, the comparison is 33.66 dB and 0.9456 for V1 against 33.89 dB and 0.9470 for V2. The authors reason that cosine normalization makes it harder for feature magnitude to cause a few pairs to dominate the attention map. The experiment supports choosing the V2 configuration for NGswin. Because the version change also changes normalization placement, the table is evidence about the package of changes rather than an isolation of cosine attention alone.
How much the training recipe contributes
The appendix compares warm-start training with training SwinIR-NG from scratch at ×3 and ×4. On Urban100 at ×3, the scratch run scores 28.71 dB and 0.8636, while the warm-start run scores 28.75 dB and 0.8639. At ×4, Urban100 moves from 26.51 dB and 0.7992 to 26.61 dB and 0.8010. On ×4 Manga109 the corresponding results are 31.02 dB and 0.9158 versus 31.09 dB and 0.9161. The gains fit the idea that a network trained to recover detail at one scale can provide useful starting features for another.
Some of the smaller test sets show a more mixed result. For ×3 Set5, scratch training gives 34.65 dB and 0.9291, while warm-start gives 34.64 dB and 0.9293. At ×3 on Set14, the SSIM values are both 0.8471, and PSNR is 30.59 dB for scratch against 30.58 dB for warm-start. The authors report that the shorter schedule is about twice as fast as training from scratch, with only the reconstruction head updated during the first 50 epochs. That comparison concerns fitting a new scale with ×2 weights already available. Learning the initial ×2 weights is a separate part of the workflow.
The paper also reports observations about normalization and regularization. The authors found that normalizing with statistics from the training data and reversing the normalization before the loss worked well for NGswin. Their half-decay learning-rate schedule fared better than cosine decay in the trials they discuss. They suggest that decay can reduce the learning rate before the network has learned adequate representations. Trials with 0.05 weight decay or 5.0 gradient clipping reduced performance, as did their trials with layer-wise learning-rate decay, dropout and drop-path. They also cite prior work that found a beneficial way to use dropout for super-resolution. Their appendix presents these training observations as specific to the tested choices and configurations.
Limitations
Limits identified by the authors
The authors delimit the task to restoration of bicubically downsampled inputs. In blind super-resolution the degradation is unknown. A system that learns from one prescribed degradation may face a different inference problem when the low-resolution input comes from another process. The paper discusses deblurring, denoising, deraining and JPEG artifact reduction as possible uses of neighboring context. These are proposed extensions. The experiments supporting the main claims reconstruct images from the bicubic test inputs.
The authors also identify a limit in SwinIR-NG's arithmetic and parameter efficiency. At full width it has more learned parameters and uses more operations than ELAN-light. The design prioritizes accuracy, while NGswin is their separate attempt to bring the operation count down. A related open question is how much higher NGswin's reconstruction scores might go if the encoder stopped downsampling. The authors expect that retaining higher-resolution features throughout could help and use their cost approximation to explain why they kept patch merging. Their experiments compare different degrees of hierarchy and the effect of SCDP in the default configuration. A fully non-hierarchical NGswin remains outside that comparison.
For the comparison with contemporary systems, the authors discuss Swin2SR, which also adopts Swin V2 and uses a continuous relative position bias. They exclude it from the lightweight quality table because it uses 3,450 training images and reports lightweight results at ×2 only, while their main SwinIR-NG results use 800 training images and cover additional scales. That decision makes the central quality table easier to interpret under its stated conditions. It also means the authors' strongest performance claim should be read against the systems they actually include and the protocol they specify.
The appendix offers visual examples of SwinIR-NG enlargements on CIFAR10 and on the ST-VQA test set. The authors suggest that sharper edges and more legible scene text could be useful for subsequent recognition. Those examples compare the appearance of the low-resolution inputs and the super-resolved outputs. The paper does not report a classification score or a scene-text question-answering score from a downstream system, nor a comparison of downstream results with other reconstruction methods.
Limits visible in the experimental setup
Mult-Adds and parameter count describe different aspects of resource use. The reported arithmetic comparison fixes the high-resolution image size and counts operations. It does not measure inference latency or energy at that size on a deployment device. Sliding neighborhoods, padding, feature rearrangement and fusion are operations that a practical implementation must carry out, and the tables offer no direct measurement of how the arithmetic rankings translate to a particular device. The paper gives a training hardware configuration and a warm-start time comparison, which answer different questions from deployment speed.
The evaluation likewise has a clear boundary. PSNR and SSIM on the Y channel show how closely brightness and structure match the known benchmark target. They leave color fidelity outside the tabulated metrics. They also do not show whether people consistently prefer the output or whether improved reconstruction aids a separate computer vision task. The visual comparisons help explain individual examples. The paper does not report uncertainty estimates or repeated training runs for the small differences between many of its entries, so close rankings are best treated as the scores of the reported runs.
Some ablations change several things together. Adding context increases parameters, and enlarging networks without context provides alternative uses of capacity rather than an exactly matched capacity control. Changing the number of context directions can change each direction's channel width. Switching from Swin V1 to V2 changes attention and normalization. In the stage study, the same count of blocks is redistributed across differently sized grids. These are informative tests of design choices, with more limited leverage for attributing every gain to a single internal mechanism.
Finally, neighborhood attention, shifted windows and the hierarchical encoder all contribute to how information can travel. The sliding operation directly compares embeddings in its configured neighborhood. Larger-scale effects can develop as multiple blocks and stages process those features. The paper shows example feature maps and the fidelity effects of altering parts of that design. It does not map every output pixel's dependence on its surroundings or establish that a broader neighborhood always gives a better reconstruction. The direction, padding and dataset comparisons show that what the additional region contains matters alongside how far it extends.
What came after
No later citing work is documented here. The authors leave open whether the same window summaries can help with unknown degradations or with restoration tasks such as denoising and deblurring. Their experiments establish results for bicubic super-resolution and leave those extensions to be tested.
Cite
Cite as Haram Choi, Jeongmin Lee and Jihoon Yang. 2023. N-Gram in Swin Transformers for Efficient Lightweight Image Super-Resolution. IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings - IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings.
@inproceedings{choi2023n,
title = {{N-Gram in Swin Transformers for Efficient Lightweight Image Super-Resolution}},
author = {Haram Choi, Jeongmin Lee and Jihoon Yang},
booktitle = {IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings - IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings},
year = {2023},
doi = {10.1109/cvpr52729.2023.00206},
eprint = {2211.11436},
archivePrefix = {arXiv},
url = {https://doi.org/10.1109/cvpr52729.2023.00206}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/choi-2023-n-gram-swin-transformers-efficient/