moose commited on
Commit
3f59f56
·
1 Parent(s): 0ee363d

Agent guidelines

Browse files
Files changed (2) hide show
  1. AGENT.md +169 -0
  2. CLAUDE.md +169 -0
AGENT.md ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AGENT.md
2
+
3
+ This file provides guidance to AI coding agents when working with code in this repository.
4
+
5
+ ## Project Overview
6
+
7
+ This is a Gradio Space that implements "Next Scene" cinematic image generation using Qwen-Image-Edit-2509 with LoRA fine-tuning. The application generates visually progressive image sequences with natural cinematic transitions from frame to frame, optimized for fast 4-step inference.
8
+
9
+ **Key Model Components:**
10
+ - Base model: `Qwen/Qwen-Image-Edit-2509` (image editing diffusion model)
11
+ - Accelerated transformer: `linoyts/Qwen-Image-Edit-Rapid-AIO` (4-step optimized variant)
12
+ - LoRA adapter: `lovis93/next-scene-qwen-image-lora-2509` (cinematic progression fine-tune)
13
+ - Text encoder: `Qwen2.5-VL-72B-Instruct` (via Hugging Face InferenceClient for prompt enhancement)
14
+
15
+ ## Running the Application
16
+
17
+ **Start the Gradio interface:**
18
+ ```bash
19
+ python app.py
20
+ ```
21
+
22
+ **Install dependencies:**
23
+ ```bash
24
+ pip install -r requirements.txt
25
+ ```
26
+
27
+ The app requires GPU access. It uses the `@spaces.GPU` decorator for Hugging Face Spaces zero-GPU allocation.
28
+
29
+ ## Architecture
30
+
31
+ ### Pipeline Flow
32
+
33
+ 1. **Input Processing** (`app.py:infer`):
34
+ - Accepts input images via Gradio Gallery (filepath-based)
35
+ - Optional prompt rewriting using `Qwen2.5-VL-72B-Instruct` API
36
+ - Automatic "Next Scene" prompt generation from images
37
+
38
+ 2. **Image Generation** (`qwenimage/pipeline_qwenimage_edit_plus.py`):
39
+ - Custom pipeline extending `DiffusionPipeline`
40
+ - Encodes images using VAE at 1024x1024 for latents
41
+ - Encodes conditioning images at 384x384 for text encoder
42
+ - Packs latents into 2x2 patches (latent dims must be divisible by 2)
43
+ - Uses `FlowMatchEulerDiscreteScheduler` for denoising
44
+
45
+ 3. **Optimization** (`optimization.py`):
46
+ - Ahead-of-time (AOT) compilation using `torch.export` and `spaces.aoti_compile`
47
+ - Dynamic shapes for variable sequence lengths
48
+ - Custom inductor configs for performance (max_autotune, cudagraphs)
49
+ - FlashAttention 3 integration via `QwenDoubleStreamAttnProcessorFA3`
50
+
51
+ 4. **Output Handling**:
52
+ - Saves outputs to `outputs/` directory with unique timestamps
53
+ - Maintains 20-image history gallery
54
+ - Optional video generation via `multimodalart/wan-2-2-first-last-frame` Space
55
+
56
+ ### Custom QwenImage Components
57
+
58
+ **Location:** `qwenimage/` package
59
+
60
+ - `pipeline_qwenimage_edit_plus.py` - Main diffusion pipeline with LoRA support
61
+ - `transformer_qwenimage.py` - Custom transformer model with cache management
62
+ - `qwen_fa3_processor.py` - FlashAttention 3 attention processor
63
+
64
+ **Key architectural features:**
65
+ - Latent packing/unpacking for 2x2 patch processing
66
+ - Multi-image conditioning support
67
+ - True CFG (classifier-free guidance) with separate pos/neg paths
68
+ - Dual-stream attention with rotary embeddings
69
+ - Cache contexts for conditional/unconditional forward passes
70
+
71
+ ### Prompt Engineering
72
+
73
+ **Two-stage prompt system:**
74
+
75
+ 1. **Edit Instruction Rewriter** (`SYSTEM_PROMPT`):
76
+ - Normalizes user prompts into professional editing instructions
77
+ - Handles text replacement (requires quotes), object manipulation, style transfer
78
+ - Used when `rewrite_prompt=True` checkbox is enabled
79
+
80
+ 2. **Next Scene Generator** (`NEXT_SCENE_SYSTEM_PROMPT`):
81
+ - Automatically suggests cinematic camera movements
82
+ - Focus on visual progression (dolly, pan, zoom, framing changes)
83
+ - Auto-triggers when input images change
84
+
85
+ Both use `Qwen2.5-VL-72B-Instruct` via Hugging Face InferenceClient with Nebius provider. Requires `HF_TOKEN` environment variable.
86
+
87
+ ## Important Implementation Details
88
+
89
+ ### Image Dimension Handling
90
+
91
+ Images are automatically resized based on `calculate_dimensions()` function:
92
+ - VAE images: resized to maintain 1024×1024 area (1,048,576 pixels)
93
+ - Condition images: resized to maintain 384×384 area (147,456 pixels)
94
+ - Output dimensions must be divisible by 16 (vae_scale_factor × 2)
95
+ - Height/width default to `None` which auto-calculates from input aspect ratio
96
+
97
+ ### LoRA Integration
98
+
99
+ The pipeline fuses the "next-scene" LoRA adapter at initialization:
100
+ ```python
101
+ pipe.load_lora_weights("lovis93/next-scene-qwen-image-lora-2509", ...)
102
+ pipe.set_adapters(["next-scene"], adapter_weights=[1.])
103
+ pipe.fuse_lora(adapter_names=["next-scene"], lora_scale=1.)
104
+ pipe.unload_lora_weights()
105
+ ```
106
+
107
+ After fusion, the adapter weights are merged into the base model and cannot be unfused.
108
+
109
+ ### Video Generation Integration
110
+
111
+ The `turn_into_video()` function:
112
+ - Connects to external Gradio Space `multimodalart/wan-2-2-first-last-frame`
113
+ - Requires first input image and last output image
114
+ - Uses the original prompt (or "smooth cinematic transition" fallback)
115
+ - Returns video path for display
116
+
117
+ ### Gradio Gallery Format
118
+
119
+ Input/output galleries use `type="filepath"` (string paths) rather than PIL Image tuples. Helper functions handle format compatibility for legacy tuple support.
120
+
121
+ ## Environment Variables
122
+
123
+ - `HF_TOKEN` - Required for Qwen2.5-VL API access (prompt rewriting/generation)
124
+
125
+ ## File Outputs
126
+
127
+ Generated images are saved to `outputs/` directory with format:
128
+ ```
129
+ output_{seed}_{index}_{timestamp_ms}.png
130
+ ```
131
+
132
+ ## Local Development and API Testing
133
+
134
+ The `custom/` directory is fully gitignored and used for local development files. Specifically, it contains:
135
+
136
+ - **API client scripts** - For testing the Gradio Space remotely via API after deployment to Hugging Face
137
+ - **`API_GUIDE.txt`** - Auto-generated Gradio API documentation showing endpoint signatures and example usage
138
+ - **Local testing environments** - Virtual environments or test data that shouldn't be committed
139
+
140
+ **API Integration Pattern:**
141
+ Once the Space is deployed to Hugging Face, you can interact with it programmatically using `gradio_client`:
142
+
143
+ ```python
144
+ from gradio_client import Client, handle_file
145
+
146
+ client = Client("Sneak-Moose/Qwen-Image-Edit-next-scene")
147
+ result = client.predict(
148
+ images=[],
149
+ prompt="Next Scene: Camera dollies forward...",
150
+ seed=42,
151
+ randomize_seed=False,
152
+ true_guidance_scale=1.0,
153
+ num_inference_steps=4,
154
+ height=1024,
155
+ width=1024,
156
+ rewrite_prompt=False,
157
+ api_name="/infer"
158
+ )
159
+ ```
160
+
161
+ The `custom/API_GUIDE.txt` contains full documentation of all available endpoints including `/infer`, `/turn_into_video`, `/suggest_next_scene_prompt`, and utility functions.
162
+
163
+ ## Development Notes
164
+
165
+ - The model loads on startup and applies AOT compilation during first inference
166
+ - Compilation uses dynamic shapes to support variable text/image sequence lengths
167
+ - The transformer uses custom cache contexts ("cond"/"uncond") to optimize CFG passes
168
+ - True CFG applies norm-based rescaling: `comb_pred * (cond_norm / noise_norm)`
169
+ - FlashAttention 3 processor must be set before compilation
CLAUDE.md ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Project Overview
6
+
7
+ This is a Gradio Space that implements "Next Scene" cinematic image generation using Qwen-Image-Edit-2509 with LoRA fine-tuning. The application generates visually progressive image sequences with natural cinematic transitions from frame to frame, optimized for fast 4-step inference.
8
+
9
+ **Key Model Components:**
10
+ - Base model: `Qwen/Qwen-Image-Edit-2509` (image editing diffusion model)
11
+ - Accelerated transformer: `linoyts/Qwen-Image-Edit-Rapid-AIO` (4-step optimized variant)
12
+ - LoRA adapter: `lovis93/next-scene-qwen-image-lora-2509` (cinematic progression fine-tune)
13
+ - Text encoder: `Qwen2.5-VL-72B-Instruct` (via Hugging Face InferenceClient for prompt enhancement)
14
+
15
+ ## Running the Application
16
+
17
+ **Start the Gradio interface:**
18
+ ```bash
19
+ python app.py
20
+ ```
21
+
22
+ **Install dependencies:**
23
+ ```bash
24
+ pip install -r requirements.txt
25
+ ```
26
+
27
+ The app requires GPU access. It uses the `@spaces.GPU` decorator for Hugging Face Spaces zero-GPU allocation.
28
+
29
+ ## Architecture
30
+
31
+ ### Pipeline Flow
32
+
33
+ 1. **Input Processing** (`app.py:infer`):
34
+ - Accepts input images via Gradio Gallery (filepath-based)
35
+ - Optional prompt rewriting using `Qwen2.5-VL-72B-Instruct` API
36
+ - Automatic "Next Scene" prompt generation from images
37
+
38
+ 2. **Image Generation** (`qwenimage/pipeline_qwenimage_edit_plus.py`):
39
+ - Custom pipeline extending `DiffusionPipeline`
40
+ - Encodes images using VAE at 1024x1024 for latents
41
+ - Encodes conditioning images at 384x384 for text encoder
42
+ - Packs latents into 2x2 patches (latent dims must be divisible by 2)
43
+ - Uses `FlowMatchEulerDiscreteScheduler` for denoising
44
+
45
+ 3. **Optimization** (`optimization.py`):
46
+ - Ahead-of-time (AOT) compilation using `torch.export` and `spaces.aoti_compile`
47
+ - Dynamic shapes for variable sequence lengths
48
+ - Custom inductor configs for performance (max_autotune, cudagraphs)
49
+ - FlashAttention 3 integration via `QwenDoubleStreamAttnProcessorFA3`
50
+
51
+ 4. **Output Handling**:
52
+ - Saves outputs to `outputs/` directory with unique timestamps
53
+ - Maintains 20-image history gallery
54
+ - Optional video generation via `multimodalart/wan-2-2-first-last-frame` Space
55
+
56
+ ### Custom QwenImage Components
57
+
58
+ **Location:** `qwenimage/` package
59
+
60
+ - `pipeline_qwenimage_edit_plus.py` - Main diffusion pipeline with LoRA support
61
+ - `transformer_qwenimage.py` - Custom transformer model with cache management
62
+ - `qwen_fa3_processor.py` - FlashAttention 3 attention processor
63
+
64
+ **Key architectural features:**
65
+ - Latent packing/unpacking for 2x2 patch processing
66
+ - Multi-image conditioning support
67
+ - True CFG (classifier-free guidance) with separate pos/neg paths
68
+ - Dual-stream attention with rotary embeddings
69
+ - Cache contexts for conditional/unconditional forward passes
70
+
71
+ ### Prompt Engineering
72
+
73
+ **Two-stage prompt system:**
74
+
75
+ 1. **Edit Instruction Rewriter** (`SYSTEM_PROMPT`):
76
+ - Normalizes user prompts into professional editing instructions
77
+ - Handles text replacement (requires quotes), object manipulation, style transfer
78
+ - Used when `rewrite_prompt=True` checkbox is enabled
79
+
80
+ 2. **Next Scene Generator** (`NEXT_SCENE_SYSTEM_PROMPT`):
81
+ - Automatically suggests cinematic camera movements
82
+ - Focus on visual progression (dolly, pan, zoom, framing changes)
83
+ - Auto-triggers when input images change
84
+
85
+ Both use `Qwen2.5-VL-72B-Instruct` via Hugging Face InferenceClient with Nebius provider. Requires `HF_TOKEN` environment variable.
86
+
87
+ ## Important Implementation Details
88
+
89
+ ### Image Dimension Handling
90
+
91
+ Images are automatically resized based on `calculate_dimensions()` function:
92
+ - VAE images: resized to maintain 1024×1024 area (1,048,576 pixels)
93
+ - Condition images: resized to maintain 384×384 area (147,456 pixels)
94
+ - Output dimensions must be divisible by 16 (vae_scale_factor × 2)
95
+ - Height/width default to `None` which auto-calculates from input aspect ratio
96
+
97
+ ### LoRA Integration
98
+
99
+ The pipeline fuses the "next-scene" LoRA adapter at initialization:
100
+ ```python
101
+ pipe.load_lora_weights("lovis93/next-scene-qwen-image-lora-2509", ...)
102
+ pipe.set_adapters(["next-scene"], adapter_weights=[1.])
103
+ pipe.fuse_lora(adapter_names=["next-scene"], lora_scale=1.)
104
+ pipe.unload_lora_weights()
105
+ ```
106
+
107
+ After fusion, the adapter weights are merged into the base model and cannot be unfused.
108
+
109
+ ### Video Generation Integration
110
+
111
+ The `turn_into_video()` function:
112
+ - Connects to external Gradio Space `multimodalart/wan-2-2-first-last-frame`
113
+ - Requires first input image and last output image
114
+ - Uses the original prompt (or "smooth cinematic transition" fallback)
115
+ - Returns video path for display
116
+
117
+ ### Gradio Gallery Format
118
+
119
+ Input/output galleries use `type="filepath"` (string paths) rather than PIL Image tuples. Helper functions handle format compatibility for legacy tuple support.
120
+
121
+ ## Environment Variables
122
+
123
+ - `HF_TOKEN` - Required for Qwen2.5-VL API access (prompt rewriting/generation)
124
+
125
+ ## File Outputs
126
+
127
+ Generated images are saved to `outputs/` directory with format:
128
+ ```
129
+ output_{seed}_{index}_{timestamp_ms}.png
130
+ ```
131
+
132
+ ## Local Development and API Testing
133
+
134
+ The `custom/` directory is fully gitignored and used for local development files. Specifically, it contains:
135
+
136
+ - **API client scripts** - For testing the Gradio Space remotely via API after deployment to Hugging Face
137
+ - **`API_GUIDE.txt`** - Auto-generated Gradio API documentation showing endpoint signatures and example usage
138
+ - **Local testing environments** - Virtual environments or test data that shouldn't be committed
139
+
140
+ **API Integration Pattern:**
141
+ Once the Space is deployed to Hugging Face, you can interact with it programmatically using `gradio_client`:
142
+
143
+ ```python
144
+ from gradio_client import Client, handle_file
145
+
146
+ client = Client("Sneak-Moose/Qwen-Image-Edit-next-scene")
147
+ result = client.predict(
148
+ images=[],
149
+ prompt="Next Scene: Camera dollies forward...",
150
+ seed=42,
151
+ randomize_seed=False,
152
+ true_guidance_scale=1.0,
153
+ num_inference_steps=4,
154
+ height=1024,
155
+ width=1024,
156
+ rewrite_prompt=False,
157
+ api_name="/infer"
158
+ )
159
+ ```
160
+
161
+ The `custom/API_GUIDE.txt` contains full documentation of all available endpoints including `/infer`, `/turn_into_video`, `/suggest_next_scene_prompt`, and utility functions.
162
+
163
+ ## Development Notes
164
+
165
+ - The model loads on startup and applies AOT compilation during first inference
166
+ - Compilation uses dynamic shapes to support variable text/image sequence lengths
167
+ - The transformer uses custom cache contexts ("cond"/"uncond") to optimize CFG passes
168
+ - True CFG applies norm-based rescaling: `comb_pred * (cond_norm / noise_norm)`
169
+ - FlashAttention 3 processor must be set before compilation