Repository navigation
fix(upscale): upscale webtoon strips and split spreads, and stop the fp16 fused path rejecting itself - #94
Merged
Merged
Conversation
…lified Both cases were decided wrongly before any pixels were computed, and each failure looked like "upscaling just does not work on this book" in the log. Split spreads: a wide page is drawn as two half cells with ContentScale.Crop, so the page is enlarged until it covers the cell, while the cell itself is exactly half the spread's aspect. The trigger measured the cell and kept the smaller of the two ratios, i.e. exactly half the painted scale: a 1760x1300 spread drawn at ~1.8x in a 1600x2364 cell read as 0.9x and was never queued, although the same page without the split (fitted, 0.9x) legitimately was not. With "split wide pages" on, that switched upscaling off for every spread in a book — and because the trigger ran before the cache lookup, even the runs that already existed on disk were thrown away. The request now records that it is cropped and the trigger takes the larger ratio there, the same rule that makes a fitted cell take the smaller one; the cache lookup moved ahead of the trigger so a layout change cannot hide a page that is already enhanced. Webtoon strips: a 720x5632 page was refused outright by the engine's 4096 output edge, which was sized for the fused path holding one source page and its 2x result in VRAM at once. Any strip is 2x taller than that, so no webtoon page could ever be upscaled; and the refusal arrived after the caller had already allocated the 2x bitmap (65 MB for that page), with three refusals in a row tripping the enhancer's circuit breaker and turning the rest of the book off. A page taller than one fused pass is now processed as stacked vertical bands: each band lifts the model's receptive field above and below itself and writes the whole lifted region, so the rows at a seam are computed again by the band that has the context they need and no seam is left behind. The staged fallback runs the same bands, and it never needed a page-sized allocation anyway. What is still refused is a page whose output bitmap cannot fit the budget (4096 wide, 16384 tall, 20 MP). That budget now lives in Waifu2xBridge and is applied by the trigger as well, so an impossible page is never queued, never allocates its bitmap, and never counts as a failed run towards the breaker.
A spread split into two cells is one enhancement shown twice, so the badge had to belong to exactly one cell — it was pinned to the first half. Turning to the second half then left the page waiting with the first half off screen and no indicator anywhere, which reads as "this page is doing nothing". The badge now belongs to the cell the host reports as visible: the deck's front slot, or the pager's current index. Both halves still share the single run, so exactly one badge is shown at a time and it is always the half on screen. `cellVisible` is nullable on purpose — a call site with no notion of a current cell keeps the old rule instead of painting a badge on both halves at once.
A band computes kPrepadding source rows above and below its own range because the network needs that context at a seam, but process() wrote back the whole lifted region. Bands run top to bottom, so the next band's *top* padding — rows computed against a clamp at its own first row — landed on top of the previous band's correctly computed core rows. Every seam therefore carried 7 source rows (14 output rows) of duplicated edge content: a thin smear line on a webtoon strip. The write order made it look fixed, because the bottom padding of the previous band was genuinely replaced by the next band's core. Each band now commits exactly [y0, y1) in output rows: write_tile clips at the window (still range-checking the rows it does not write, so a broken run is not committed as valid), run_fused clips its download memcpy and its alpha scan to the same window, and run_staged_band passes it through. Every committed row is then computed with real context on both sides, only the page's own top and bottom rows stay clamped, and the order of the bands no longer matters — the previous shape would have needed per-band buffers to be correct. A whole page (unbanded) passes write_from=0/write_to=2*h, so nothing changes for it.
…reads it The fused path never worked on an fp16 engine: every run logged `probe tile 142x142x3 = 0.000 0.000 0.000` where the fp32 run of the same self-test image logged 0.976, so the preproc had built an all-zero tile and the network answered with its bias constant (2.582 / 3.285). The page then failed its alpha self-check and the engine silently dropped to the staged CPU path — 12 s/page instead of 9 s/page, and only fp32 ever got the fused path. Cause: ncnn applies opt.use_fp16_storage to record_clone as well. On an fp16 engine the raw ARGB page went into VRAM as half values, while the preproc shader decodes the buffer as packed uint32 pixels — every channel came out of a half's low byte, i.e. zero. The earlier comment assumed a clone was a raw byte copy; only record_upload was known to cast. Byte transfers now run with raw_opt (fp16 packed/storage and bf16 off), so the page and the result texture stay fp32 while the network keeps whatever storage precision the engine chose. Also pins the network result to fp32 (cast_type_to 1) before the postproc. With cast_type_to 0 an fp16 engine handed back halves and selected the fp16 postproc shader, which decodes through unpackHalf2x16 — a variant no device has ever run, and it was the second candidate for the alpha-0 failure signature. The widening is exact and costs one cheap GPU pass per tile; the fp16 shader stays only as a fallback for a driver that ignores the request. Diagnostics for the next device run: the upload log now prints the texture's elemsize/pack, and the preproc probe samples the tile centre next to the corner (pixel 0 is a replicated edge pixel, so a black corner could pass a dead dispatch off as a working one).
"When the path says staged" is the only signal an fp16 failure leaves behind: load_and_verify() turns the fused shaders off for any reason at all, and the three reasons this path has actually failed for (half-encoded upload, dead preproc dispatch, fp16 network overflow) look identical from the log. Two probes now separate them on a self-test sized page: - the uploaded page is cloned back and compared against the caller's bytes (mismatch count plus the first differing pixel as raw words), so a cast on the way into VRAM is visible instead of being inferred from a zero tile; - the preproc tile and the network result are reported as min/max plus a non-finite count. A dead dispatch is min=max=0, a network fed a zero tile answers a constant near its bias, and non-finite values mean the GPU fp16 path itself overflowed - the one case no shader change can rescue. Both probes stay out of the way of real pages: the byte comparison only runs when the page is self-test sized (<= 60k pixels) and min/max costs one pass over the first tile only.
…ing it The new self-test probes pinned the fp16 failure down: the page upload is now byte-exact (`upload verify: 0 differing`, elemsize 4, pack 1) and the preproc tile is correct (`min=0.000 max=1.000`), but the value the postproc read from the "widened" network result came back as -2.7e36 .. 4.3e37 with no NaNs. That is a buffer of halves being read as floats: convert_packing(cast_type_to=1) returned a Mat that reports fp32 element size while still holding fp16 data. The postproc then missed its 4.0 plausibility bound on every pixel and wrote the alpha-0 sentinel, which load_and_verify() reads as "fused is broken" and turns the whole fused path off — the reason every fp16 device has been running staged CPU (~10-12 s/page) while fp32 got the shaders. There is nothing to cast. When the network hands back an elempack-1 tensor it now goes to the postproc as it is, and the fp16 variant of that shader decodes the halves; only a packed result is unpacked, and then cast_type_to=0 keeps its real type instead of claiming one. The page download still widens to fp32 on the way back, so nothing downstream sees halves. As a side effect the fp32 path drops a no-op GPU pass per tile. Kept from the diagnosis build: the upload round-trip comparison, the preproc and network min/max probes, and a new probe of the raw network tensor plus the unpacked tile's real elemsize/elempack — that is what separates "the cast lied about the type" from "the GPU net itself overflows", which no change here could rescue. The previous commit also carries the repair of the em dashes that an earlier PowerShell rewrite mangled into mojibake.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Two independent reasons why waifu2x never ran on the pages people actually read,
plus three follow-ups found while verifying them.
1. Webtoon strips were refused, not skipped
The decision layer judged long strips correctly (
720x5632 target=1600x12507 -> upscale=true), but the native layer refused anything whose 2x result exceeded4096 on an edge:
page too large to upscale: 720x5632 -> 1440x11264 (limit 4096). So every strip allocated a 65 MB bitmap, was refused, and after threesuch pages
MAX_CONSECUTIVE_FAILUREStripped the circuit breaker that switchesupscaling off until the reader is reopened.
Pages taller than one fused pass are now processed in bands of 1024 source rows,
each with its own VRAM upload, and each band lifts
kPrepaddingrows above andbelow as receptive-field context. Only the rows a band owns are written back:
committing the lifted rows too made the next band's top padding — computed
against a clamp at its own edge — land on the previous band's correct core rows,
i.e. 7 source rows of duplicated edge content per seam. The commit window
(
write_from/write_toinwrite_tile,run_staged_band,run_fused) makesthe band order irrelevant and leaves only the page's own top and bottom rows
clamped. The page budget is now (
kMaxPageOutputWidth,kMaxPageOutputHeight,kMaxPageOutputPixels), mirrored inWaifu2xBridge.MAX_OUTPUT_*so thedecision layer rejects an impossible page before allocating anything.
2. Split spreads were measured at half their real magnification
A
Halfcell draws the whole page withContentScale.Crop, so the real factoris
cellH / srcH(the width is cropped away);UpscaleDecisiontookmin()ofboth ratios and therefore always landed at half of it:
src=1760x1300 target=1600x2364 -> upscale=false. The same page without the split gavetarget=2166x1600 -> upscale=trueand enhanced fine.EnhancementDecoder.applyTo(..., cover)now carriescover = half != null,displayScaletakesmax()instead ofmin()in that case, andfitsEngineBudgetapplies the same page budget as the native side. The cache lookup also moved
before the decision, so an already enhanced full page is reused in split mode
instead of being recomputed (and the preload path no longer pre-warms with
displayMetricsratios that could never qualify).3. The badge belonged to a half that was no longer on screen
A split page is one enhancement shown in two cells, so only one cell may show
the processing badge. It was pinned to the first half; turning to the second
left the page waiting with the first half off screen and no indicator anywhere.
ViewerPage/PageImagetake an optionalcellVisible(deck front slot, orpager current index) and the badge follows it. Nullable on purpose: a call site
with no notion of a current cell keeps the old rule instead of painting two.
4. The page was cast to half before the fused preproc decoded it
record_clonehonoursopt.use_fp16_storage, so on an fp16 engine the ARGBuint32page reached VRAM as half values while the preproc shader decoded it aspacked pixels — every channel came out of a half's low byte. The self-test tile
was all-zero (
probe tile = 0.000, versus0.976on the fp32 run of the sameimage) and the network answered with its bias constant. Byte transfers now run
with casting off.
5. The network result was cast into a lie
The second half of that failure:
convert_packing(cast_type_to=1)returned aMat reporting fp32 element size while still holding halves, so the postproc read
half pairs as floats (
min=-2.7e36 max=4.3e37, no NaNs), missed itsabs <= 4plausibility bound on every pixel and wrote the alpha-0 sentinel over the page.
Now the network's tensor goes to the postproc as it is (there is an fp16
variant, and the page download widens to fp32 on the way back); a packed result
is unpacked without changing its type.
Diagnostics kept from that hunt — upload byte round-trip, preproc and network
min/max, raw network tensor and the unpacked tile's real elemsize/elempack —
only run on self-test sized pages or the first tile, and are what makes the next
failure report name its stage instead of "path says staged".
Verification
:app:compileDebugKotlin,:app:externalNativeBuildDebug(arm64-v8a andarmeabi-v7a),
:app:assembleDebug,:app:testDebugUnitTest(227 tests) pass.UpscaleDecisionTestgains the cover-ratio, engine-budget and texture-limitcases; the texture-limit case is written with
2000x1479because2500x1120trips the width budget first.
staging is measurably faster than before.
Known gaps
2500x1120 -> 5000).The fused preproc clamps in x against a whole-page texture, so moving that
bound needs x-direction banding and a change to the shader's
srcw_px/clampcontract. The decision layer rejects those instead of counting a failure.
stagedon the test device. The probes nowclear the upload and the preproc and the cast bug is fixed, so what remains is
either the GPU network or the fp16 postproc variant — no device was available
to close that loop.
UpscaleConfig.OUTPUT_VERSIONis deliberately not bumped: no single-pageoutput changed shape, and a bump would invalidate every user's cache.