Fix token rounding

This commit is contained in:
moosecrap 2026-07-23 02:22:30 -07:00
parent 77a88c093d
commit a2cc56200c

View File

@ -39,30 +39,31 @@ def parse_indices(indices_str: str) -> List[int]:
def calculate_patch_dimensions(orig_w: int, orig_h: int, target_tokens: int = 70):
"""
Calculates optimal pixel dimensions to hit a token budget of at least target_tokens.
The algorithm tries anchoring both Width and Height to find the smallest patch
count that satisfies the target while preserving aspect ratio.
Validates budget based on actual rounded pixel dimensions to avoid float precision errors.
"""
ar = orig_w / orig_h
# Case A: Width is the anchor (non-padded)
w_anchor = 1
while True:
w = w_anchor * 48
h = w / ar
hp = math.ceil(h / 48)
if w_anchor * hp >= target_tokens:
res_a = {"w": w, "h": round(h), "tokens": w_anchor * hp}
w_px = w_anchor * 48
h_px = round(w_px / ar)
# Calculate actual tokens based on resulting pixel dimensions
tokens = math.ceil(w_px / 48) * math.ceil(h_px / 48)
if tokens >= target_tokens:
res_a = {"w": w_px, "h": h_px, "tokens": tokens}
break
w_anchor += 1
# Case B: Height is the anchor (non-padded)
h_anchor = 1
while True:
h = h_anchor * 48
w = h * ar
wp = math.ceil(w / 48)
if h_anchor * wp >= target_tokens:
res_b = {"w": round(w), "h": h, "tokens": h_anchor * wp}
h_px = h_anchor * 48
w_px = round(h_px * ar)
# Calculate actual tokens based on resulting pixel dimensions
tokens = math.ceil(w_px / 48) * math.ceil(h_px / 48)
if tokens >= target_tokens:
res_b = {"w": w_px, "h": h_px, "tokens": tokens}
break
h_anchor += 1