Skip to content

fix: dtype alignment for attention mask and add bf16 support - #14

Merged
Tohrusky merged 11 commits into
EutropicAI:mainfrom
NULL204:main
Jul 9, 2026
Merged

fix: dtype alignment for attention mask and add bf16 support#14
Tohrusky merged 11 commits into
EutropicAI:mainfrom
NULL204:main

Conversation

@NULL204

@NULL204 NULL204 commented Jun 16, 2026

Copy link
Copy Markdown
Member

This pull request adds support for bfloat16 (bf16) precision throughout the model loading and inference pipeline, providing users with an alternative to fp16 for half-precision inference. It also ensures proper dtype handling in attention modules and data conversions, improving numerical stability and compatibility with various hardware and models.

Precision and dtype support:

  • Added a bf16 (bfloat16) option to model loading interfaces (from_pretrained, from_config, and CCBaseModel), which takes precedence over fp16 and is used throughout the codebase for half-precision inference. This includes updating documentation and parameter lists to reflect the new option. [1] [2] [3] [4] [5] [6] [7] [8] [9]
  • Updated model initialization and inference code to consistently use the correct half-precision dtype (torch.bfloat16 or torch.float16), with fallback to fp32 if half-precision is not supported.
  • Modified image and tensor conversion logic in inference methods to cast outputs back to float32 before converting to NumPy arrays, ensuring compatibility since NumPy does not support bfloat16. [1] [2] [3] [4] [5]

Attention module stability:

  • Ensured that relative position bias and attention masks are cast to the same dtype as attention tensors in several transformer-based architectures, preventing dtype mismatches and potential computation errors. [1] [2] [3] [4]

NULL204 and others added 2 commits June 17, 2026 00:44
DAT/HAT/SwinIR window attention added the float32 attention mask and
relative position bias directly onto a half-precision attn tensor, which
type-promoted the result back to float32 and then failed at the attn @ v
matmul with "expected scalar type Half but found Float" (same under bf16).
Cast both to attn.dtype before adding.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Add a bf16 flag alongside fp16 to the model base class and AutoModel
(from_pretrained / from_config). Weights and inputs are cast through a
shared half_dtype, with bf16 taking precedence over fp16. bf16 has the
same dynamic range as fp32, so it avoids the fp16 overflow that produces
NaN/black output on transformer SR models (e.g. DAT, SwinIR) while
keeping fp16's memory savings.

Also cast model output back to float32 before converting to numpy, since
numpy has no bfloat16 dtype.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings June 16, 2026 16:51

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

This PR adds bfloat16 (bf16) support alongside fp16 for inference, aiming to reduce overflow/NaN issues on some SR/transformer models while ensuring outputs can be converted to NumPy safely.

Changes:

  • Add bf16 option to model construction APIs and plumb it through to base model setup.
  • Standardize half-precision casting via self.half_dtype and update inference input/output conversions accordingly.
  • Ensure attention bias/mask tensors match attention dtype to avoid dtype-mismatch errors in half precision.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
cccv/model/base_model.py Introduces bf16 flag, half_dtype, and applies half-precision casting to model weights.
cccv/auto/model.py Exposes bf16 in factory functions and forwards it to model constructors.
cccv/model/sr_base_model.py Casts inputs to half_dtype and converts outputs to float32 before NumPy.
cccv/model/vsr_base_model.py Updates video SR inference to use half_dtype and float32 conversion before NumPy.
cccv/model/vfi/rife_model.py Updates VFI inference to use half_dtype and float32 conversion before NumPy.
cccv/model/vfi/drba_model.py Updates VFI inference to use half_dtype and float32 conversion before NumPy.
cccv/arch/sr/swinir_arch.py Casts attention bias/mask to attn.dtype for half-precision compatibility.
cccv/arch/sr/hat_arch.py Casts attention bias/mask to attn.dtype for half-precision compatibility.
cccv/arch/sr/dat_arch.py Casts attention bias/mask to attn.dtype for half-precision compatibility.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread cccv/model/base_model.py
Comment thread cccv/model/vsr_base_model.py Outdated
Comment thread cccv/model/vsr_base_model.py Outdated
Comment thread cccv/model/vfi/rife_model.py Outdated
Comment thread cccv/model/vfi/drba_model.py Outdated

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces support for bf16 (bfloat16) precision across various models and architectures, updating model initialization, inference pipelines, and attention mechanisms. Feedback on the changes suggests adding a check using torch.cuda.is_bf16_supported() during initialization to prevent runtime crashes on older GPUs that do not support bfloat16, falling back to fp16 if necessary.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread cccv/model/base_model.py
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@codecov

codecov Bot commented Jun 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.14815% with 29 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.91%. Comparing base (79725f4) to head (35cda6c).

Files with missing lines Patch % Lines
cccv/model/base_model.py 79.72% 15 Missing ⚠️
cccv/model/vsr_base_model.py 40.00% 6 Missing ⚠️
cccv/model/vfi/drba_model.py 50.00% 4 Missing ⚠️
cccv/model/vfi/rife_model.py 50.00% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #14      +/-   ##
==========================================
- Coverage   92.76%   91.91%   -0.86%     
==========================================
  Files          40       40              
  Lines        1216     1298      +82     
==========================================
+ Hits         1128     1193      +65     
- Misses         88      105      +17     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Tohrusky

Copy link
Copy Markdown
Member

need a unit test for BF16 @NULL204

NULL204 and others added 2 commits June 29, 2026 19:21
Cover the bf16 code path end to end (AutoModel.from_config(bf16=True) ->
weight/input cast -> inference -> numpy output) with an SSIM + output-size
assertion, mirroring test_sr_fp16. Runs on CPU in CI.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
CPU bfloat16 replication padding (used by tile inference) isn't
implemented in the torch build CI runs on, so test_sr_bf16 errored there.
test_sr_fp16 already guards CPU half-precision with skipif(not torch_2_4);
apply the same guard so both half-precision tests run only on the pinned
dev torch (GPU), not CI's CPU build.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@Tohrusky Tohrusky changed the title Fix dtype alignment for attention mask and add bf16 support fix: dtype alignment for attention mask and add bf16 support Jun 29, 2026
@Tohrusky
Tohrusky requested a review from Justin62628 June 29, 2026 13:22

@Justin62628 Justin62628 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Inference of bf16 on older GPUs not tested. Add fallbacks of disabling bf16 with a test inference (e.g. a 540p inference before actual run, if this inference round fails, disable bf16 as fallback).
Transformer Arch modification not tested. Add DAT, HAT, SwinIR unit test.

@Tohrusky

Tohrusky commented Jul 7, 2026

Copy link
Copy Markdown
Member

please click resolve conversation after you've done

NULL204 and others added 3 commits July 8, 2026 22:44
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 13 out of 13 changed files in this pull request and generated 2 comments.

Comment thread cccv/model/base_model.py
Comment thread tests/test_util.py
Comment thread cccv/model/vsr_base_model.py Outdated
Comment thread cccv/model/base_model.py
Comment thread cccv/auto/model.py Outdated
tile_pad: int = 8,
pad_img: Optional[Tuple[int, int]] = None,
bf16_preflight: bool = True,
bf16_preflight_size: Tuple[int, int] = (540, 960),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think use 64*64 can fasten fallback

Comment thread tests/sr/test_sr.py Outdated
assert compare_image_size(img1, img2, cfg.scale)


@pytest.mark.skipif(not torch_2_4, reason="Skip test if PyTorch version is not 2.4")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Comment thread cccv/arch/sr/dat_arch.py
@Tohrusky
Tohrusky merged commit 29d14fa into EutropicAI:main Jul 9, 2026
9 of 11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants