Repository navigation
feat: diffusion engine + Z-Image-Turbo on /v1/images/generations (#91, #99) #108
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
Open
hsliuustc0106
wants to merge
1
commit into
chore/tests-mirror-src
Choose a base branch
from
feat/diffusion-engine-zimage
base: chore/tests-mirror-src
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| .venv/ | ||
| __pycache__/ | ||
| *.pyc | ||
| *.egg-info/ | ||
| dist/ | ||
| build/ | ||
| .DS_Store | ||
| .env | ||
|
|
||
| # ===== ↑ 以上同步自 .gitignore(「从 .gitignore 同步」只重写以上部分)===== | ||
| .git/ | ||
| .hg/ | ||
| .svn/ | ||
| node_modules/ | ||
| bower_components/ | ||
| jspm_packages/ | ||
| site-packages/ | ||
| venv/ | ||
| coverage/ | ||
| htmlcov/ | ||
| lcov-report/ | ||
| cmakefiles/ | ||
| cmake-build-*/ | ||
| bazel-*/ | ||
| pods/ | ||
| deriveddata/ | ||
| storybook-static/ | ||
| playwright-report/ | ||
| test-results/ | ||
| allure-results/ | ||
| allure-report/ | ||
| cdk.out/ | ||
| *.dist-info/ | ||
| eggs/ | ||
| pip-wheel-metadata/ | ||
| wheels/ | ||
| # ----- ↑ 以上为 ZCode 默认排除规则(自定义规则请写在本行下方,不会被同步/恢复改动)----- | ||
| # 自定义规则写在下方(本行提示可删除) |
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
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
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
Empty file.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| """Family registry + request parsing for /v1/images/generations (#91). | ||
|
|
||
| CI-safe: no mflux import (config.py keeps backend imports lazy) and no | ||
| weights — resolution and defaults only. | ||
| """ | ||
|
|
||
| import unittest | ||
|
|
||
| from vllm_omni_mlx.diffusion.config import DEFAULT_MODEL, FAMILIES, resolve_model | ||
| from vllm_omni_mlx.schemas import ApiError, parse_image_generation | ||
|
|
||
|
|
||
| class ResolveModelTest(unittest.TestCase): | ||
| def test_alias_routes_to_prequant_default(self): | ||
| for alias in ("z-image-turbo", "ZImage-Turbo"): | ||
| resolved = resolve_model(alias) | ||
| self.assertEqual(resolved.family.name, "z-image-turbo") | ||
| self.assertEqual(resolved.weights_ref, DEFAULT_MODEL) | ||
| self.assertIsNone(resolved.quantize) # stored 4-bit level honored | ||
|
|
||
| def test_canonical_repo_quantizes_on_load(self): | ||
| resolved = resolve_model("Tongyi-MAI/Z-Image-Turbo") | ||
| self.assertEqual(resolved.weights_ref, "Tongyi-MAI/Z-Image-Turbo") | ||
| self.assertEqual(resolved.quantize, 4) | ||
|
|
||
| def test_prequant_mirror(self): | ||
| resolved = resolve_model(DEFAULT_MODEL) | ||
| self.assertEqual(resolved.weights_ref, DEFAULT_MODEL) | ||
| self.assertIsNone(resolved.quantize) | ||
|
|
||
| def test_unknown_ref_lists_supported(self): | ||
| with self.assertRaises(ValueError) as ctx: | ||
| resolve_model("stabilityai/stable-diffusion-xl-base-1.0") | ||
| self.assertIn("z-image-turbo", str(ctx.exception)) | ||
|
|
||
| def test_every_family_has_serving_defaults(self): | ||
| for family in FAMILIES: | ||
| self.assertGreaterEqual(family.steps, 1, family.name) | ||
|
|
||
|
|
||
| class ParseImageGenerationTest(unittest.TestCase): | ||
| def test_minimal_request(self): | ||
| req = parse_image_generation({"prompt": "a cat"}) | ||
| self.assertEqual((req.width, req.height, req.n, req.steps), (1024, 1024, 1, None)) | ||
|
|
||
| def test_size_and_diffusion_params(self): | ||
| req = parse_image_generation( | ||
| {"prompt": "a cat", "n": 2, "size": "768X1344", "steps": 9, "guidance": 0.0, "seed": 7} | ||
| ) | ||
| self.assertEqual((req.width, req.height, req.n, req.steps, req.guidance, req.seed), (768, 1344, 2, 9, 0.0, 7)) | ||
|
|
||
| def test_prompt_must_be_nonempty_string(self): | ||
| for bad in (None, 5, "", " "): | ||
| with self.assertRaises(ApiError): | ||
| parse_image_generation({"prompt": bad}) | ||
|
|
||
| def test_size_format(self): | ||
| for bad in ("1024", "ax1024", "1024x", 1024, "1024.5x1024"): | ||
| with self.assertRaises(ApiError): | ||
| parse_image_generation({"prompt": "a cat", "size": bad}) | ||
|
|
||
| def test_dimension_bounds_and_grid(self): | ||
| for bad in ("240x1024", "2112x1024", "1024x1000"): # below/above bounds, not %16 | ||
| with self.assertRaises(ApiError): | ||
| parse_image_generation({"prompt": "a cat", "size": bad}) | ||
|
|
||
| def test_n_range(self): | ||
| for bad in (0, 5, "2", True): | ||
| with self.assertRaises(ApiError): | ||
| parse_image_generation({"prompt": "a cat", "n": bad}) | ||
|
|
||
| def test_scalar_types(self): | ||
| for payload in ({"prompt": "a cat", "steps": "9"}, {"prompt": "a cat", "guidance": "0"}, {"prompt": "a cat", "seed": 1.5}): | ||
| with self.assertRaises(ApiError): | ||
| parse_image_generation(payload) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| """POST /v1/images/generations (#91): validation, auth, model listing, | ||
| and the b64/seeds response shape with a fake service. The real | ||
| Z-Image-Turbo round-trip is weight-gated in test_mflux_zimage.py.""" | ||
|
|
||
| import base64 | ||
| import unittest | ||
|
|
||
| from starlette.testclient import TestClient | ||
|
|
||
| from vllm_omni_mlx.diffusion.service import ImageResult | ||
| from vllm_omni_mlx.server import create_app | ||
|
|
||
|
|
||
| class FakeImageService: | ||
| name = "fake-image-model" | ||
| model_type = "image" | ||
|
|
||
| def __init__(self): | ||
| self.calls = [] | ||
|
|
||
| def generate(self, prompt, n=1, width=1024, height=1024, steps=None, guidance=None, seed=None): | ||
| if not prompt or not prompt.strip(): | ||
| raise ValueError("prompt must be a non-empty string") | ||
| if not 1 <= n <= 4: | ||
| raise ValueError(f"n must be between 1 and 4, got {n}") | ||
| if guidance is not None: | ||
| raise ValueError("guidance is not supported on z-image-turbo (guidance-distilled)") | ||
| self.calls.append((prompt, n, width, height, steps, guidance, seed)) | ||
| return [ | ||
| ImageResult( | ||
| png=b"\x89PNG-fake-" + bytes([i]), | ||
| seed=(seed if seed is not None else 1234) + i, | ||
| width=width, | ||
| height=height, | ||
| steps=steps or 9, | ||
| generation_time=0.5, | ||
| peak_memory_gib=1.0, | ||
| ) | ||
| for i in range(n) | ||
| ] | ||
|
|
||
|
|
||
| class ImagesEndpointTest(unittest.TestCase): | ||
| def setUp(self): | ||
| self.service = FakeImageService() | ||
| self.client = TestClient(create_app(image_service=self.service)) | ||
|
|
||
| def test_round_trip(self): | ||
| response = self.client.post( | ||
| "/v1/images/generations", json={"prompt": "a cat", "size": "512x512", "steps": 9, "seed": 42} | ||
| ) | ||
| self.assertEqual(response.status_code, 200) | ||
| body = response.json() | ||
| self.assertEqual(body["model"], "fake-image-model") | ||
| self.assertEqual(len(body["data"]), 1) | ||
| self.assertEqual(base64.b64decode(body["data"][0]["b64_json"]), b"\x89PNG-fake-\x00") | ||
| self.assertEqual(body["seeds"], [42]) | ||
| self.assertEqual(body["generation_time_ms"], [500]) | ||
| self.assertEqual(self.service.calls, [("a cat", 1, 512, 512, 9, None, 42)]) | ||
|
|
||
| def test_n_sequential_seeds(self): | ||
| body = self.client.post("/v1/images/generations", json={"prompt": "a cat", "n": 3, "seed": 10}).json() | ||
| self.assertEqual(body["seeds"], [10, 11, 12]) | ||
| self.assertEqual(len(body["data"]), 3) | ||
|
|
||
| def test_validation_errors_are_400(self): | ||
| for payload in ({"prompt": ""}, {"prompt": "a cat", "size": "1000x1024"}, {"prompt": "a cat", "n": 9}): | ||
| response = self.client.post("/v1/images/generations", json=payload) | ||
| self.assertEqual(response.status_code, 400, payload) | ||
| self.assertEqual(response.json()["error"]["type"], "invalid_request_error") | ||
|
|
||
| def test_family_capability_error_is_400(self): | ||
| response = self.client.post("/v1/images/generations", json={"prompt": "a cat", "guidance": 3.5}) | ||
| self.assertEqual(response.status_code, 400) | ||
| self.assertIn("guidance-distilled", response.json()["error"]["message"]) | ||
|
|
||
| def test_auth(self): | ||
| client = TestClient(create_app(image_service=self.service, api_key="secret")) | ||
| self.assertEqual(client.post("/v1/images/generations", json={"prompt": "a cat"}).status_code, 401) | ||
| self.assertEqual( | ||
| client.post( | ||
| "/v1/images/generations", json={"prompt": "a cat"}, headers={"Authorization": "Bearer secret"} | ||
| ).status_code, | ||
| 200, | ||
| ) | ||
|
|
||
| def test_route_absent_without_service(self): | ||
| client = TestClient(create_app()) | ||
| self.assertEqual(client.post("/v1/images/generations", json={"prompt": "a cat"}).status_code, 404) | ||
|
|
||
| def test_model_listing(self): | ||
| body = self.client.get("/v1/models").json() | ||
| self.assertIn("fake-image-model", [entry["id"] for entry in body["data"]]) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| """Real Z-Image-Turbo round-trip through the mflux seam (#99). | ||
|
|
||
| Weight-gated: runs against the local HF snapshot when cached and skips | ||
| elsewhere (CI has no weights, so a green CI run does not exercise this | ||
| file). One file = one process (CONTRIBUTING) — the 4-bit model peaks | ||
| around 6–7 GiB resident and holds it for the class. | ||
| """ | ||
|
|
||
| import os | ||
|
|
||
| # offline keeps the load fast and hang-free when the network is flaky | ||
| os.environ.setdefault("HF_HUB_OFFLINE", "1") | ||
|
|
||
| import unittest | ||
|
|
||
| from vllm_omni_mlx.diffusion.config import DEFAULT_MODEL, load_image_service | ||
|
|
||
|
|
||
| def _snapshot_cached() -> bool: | ||
| # direct check rather than snapshot_download(local_files_only=True): | ||
| # a patterns-filtered download counts as "incomplete" to the hub API | ||
| # even when every weight file is present | ||
| import glob | ||
| import os | ||
|
|
||
| pattern = os.path.expanduser( | ||
| f"~/.cache/huggingface/hub/models--{DEFAULT_MODEL.replace('/', '--')}/snapshots/*/transformer/*.safetensors" | ||
| ) | ||
| return bool(glob.glob(pattern)) | ||
|
|
||
|
|
||
| @unittest.skipUnless(_snapshot_cached(), f"{DEFAULT_MODEL} not in the local HF cache") | ||
| class ZImageTurboE2ETest(unittest.TestCase): | ||
| """512² × 9 steps keeps the run quick while exercising the full path: | ||
| pre-quant load → text encode → 9 denoise steps → VAE decode → PNG.""" | ||
|
|
||
| @classmethod | ||
| def setUpClass(cls): | ||
| import mlx.core as mx | ||
|
|
||
| cls.mx = mx | ||
| cls.service = load_image_service(DEFAULT_MODEL) | ||
| cls.prompt = "a crisp red apple on a wooden table, studio light" | ||
|
|
||
| @classmethod | ||
| def tearDownClass(cls): | ||
| # donor release: one heavy thing at a time on a 16 GB machine | ||
| cls.service = None | ||
| cls.mx.clear_cache() | ||
|
|
||
| def test_generate_png_shape_and_gate(self): | ||
| (result,) = self.service.generate(self.prompt, width=512, height=512, steps=9, seed=20261007) | ||
| self.assertTrue(result.png.startswith(b"\x89PNG"), "output must be a PNG") | ||
| self.assertGreater(len(result.png), 50_000, "a 512² PNG should not be tiny (non-degenerate gate)") | ||
| self.assertEqual((result.width, result.height, result.steps), (512, 512, 9)) | ||
| self.assertEqual(result.seed, 20261007) | ||
| self.assertGreater(result.generation_time, 0.1) | ||
| print( | ||
| f"\nz-image-turbo 512x512/9 steps: {result.generation_time:.2f}s, " | ||
| f"peak {result.peak_memory_gib:.2f} GiB, png {len(result.png) / 1e6:.2f} MB", | ||
| flush=True, | ||
| ) | ||
|
|
||
| def test_same_seed_reproduces_bytes(self): | ||
| first = self.service.generate(self.prompt, width=512, height=512, steps=9, seed=7)[0].png | ||
| second = self.service.generate(self.prompt, width=512, height=512, steps=9, seed=7)[0].png | ||
| self.assertEqual( | ||
| first, second, "same-seed calls must reproduce byte-identical PNGs (fp16 fusion-flip precedent: characterize if this trips)" | ||
| ) | ||
|
|
||
| def test_family_capability_validation(self): | ||
| with self.assertRaises(ValueError): | ||
| self.service.generate(self.prompt, width=512, height=512, guidance=3.5) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
Oops, something went wrong.
Oops, something went wrong.
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.
[P3] Weight-gated class skips the
ReleaseAfterClasstaxonomy. Every weight-gated class in the repo inheritstests/_teardown.ReleaseAfterClass(16 TTS classes in this tree;tests/test_asr.py:286on main). The hand-rolledtearDownClassis functionally equivalent today but diverges from the documented mechanism and won't pick up futureReleaseAfterClassadditions. Fix:class ZImageTurboE2ETest(ReleaseAfterClass, unittest.TestCase):and drop the customtearDownClass.