fffiloni commited on
Commit
2c2e958
·
verified ·
1 Parent(s): 5dc6179

Update app_wip.py

Browse files
Files changed (1) hide show
  1. app_wip.py +33 -45
app_wip.py CHANGED
@@ -18,6 +18,7 @@ from utils.dataset import TextDataset
18
  from utils.misc import set_seed
19
  from demo_utils.memory import get_cuda_free_memory_gb, DynamicSwapInstaller
20
 
 
21
  # -------------------------------------------------------------------
22
  # Download checkpoints once when the Space starts
23
  # -------------------------------------------------------------------
@@ -41,6 +42,7 @@ snapshot_download(
41
  local_dir="./checkpoints/Reward-Forcing-T2V-1.3B",
42
  )
43
 
 
44
  # === Paths ===
45
  CONFIG_PATH = "configs/reward_forcing.yaml"
46
  CHECKPOINT_PATH = "checkpoints/Reward-Forcing-T2V-1.3B/rewardforcing.pt"
@@ -63,7 +65,7 @@ def reward_forcing_inference(
63
  Inline / simplified version of inference.py:
64
  - single GPU
65
  - text-to-video only
66
- - one .txt file = N prompts, but we return only the first generated video
67
  """
68
  logs = ""
69
 
@@ -77,7 +79,7 @@ def reward_forcing_inference(
77
 
78
  torch.set_grad_enabled(False)
79
 
80
- # --------------------- Stage 1: model & config init ---------------------
81
  progress(0.05, desc="Init: loading config")
82
  logs += "Loading config...\n"
83
  config = OmegaConf.load(CONFIG_PATH)
@@ -87,10 +89,8 @@ def reward_forcing_inference(
87
  progress(0.15, desc="Init: creating pipeline")
88
  logs += "Creating pipeline...\n"
89
  if hasattr(config, "denoising_step_list"):
90
- # few-step sampling pipeline
91
  pipeline = CausalInferencePipeline(config, device=device)
92
  else:
93
- # full diffusion pipeline
94
  pipeline = CausalDiffusionInferencePipeline(config, device=device)
95
 
96
  progress(0.35, desc="Init: loading checkpoint")
@@ -124,7 +124,7 @@ def reward_forcing_inference(
124
  dataset, batch_size=1, sampler=sampler, num_workers=0, drop_last=False
125
  )
126
 
127
- # --------------------- Make a clean output directory ---------------------
128
  progress(0.7, desc="Cleaning output folder")
129
  output_folder = os.path.join(
130
  output_root, f"rewardforcing-{num_output_frames}f", checkpoint_step
@@ -133,8 +133,7 @@ def reward_forcing_inference(
133
  os.makedirs(output_folder, exist_ok=True)
134
  logs += f"Output directory: {output_folder}\n"
135
 
136
- # --------------------- Stage 2: inference loop ---------------------
137
- # Gradio can track tqdm progress on iterable loops
138
  for i, batch_data in progress.tqdm(
139
  enumerate(dataloader),
140
  total=num_prompts,
@@ -153,17 +152,13 @@ def reward_forcing_inference(
153
 
154
  all_video = []
155
 
156
- # TEXT-TO-VIDEO only (no I2V here)
157
  prompt = batch["prompts"][0]
158
  extended_prompt = batch.get("extended_prompts", [None])[0]
159
- if extended_prompt is not None:
160
- prompts = [extended_prompt]
161
- else:
162
- prompts = [prompt]
163
 
164
  initial_latent = None
165
 
166
- # Noise tensor shape matches WAN2 expected latent dims
167
  sampled_noise = torch.randn(
168
  [1, num_output_frames, 16, 60, 104],
169
  device=device,
@@ -172,7 +167,7 @@ def reward_forcing_inference(
172
 
173
  logs += f"Generating for prompt: {prompt[:80]}...\n"
174
 
175
- # Run WAN inference
176
  video, latents = pipeline.inference(
177
  noise=sampled_noise,
178
  text_prompts=prompts,
@@ -183,14 +178,10 @@ def reward_forcing_inference(
183
 
184
  current_video = rearrange(video, "b t c h w -> b t h w c").cpu()
185
  all_video.append(current_video)
186
-
187
- # convert to uint8 *after* concatenation
188
  video = 255.0 * torch.cat(all_video, dim=1)
189
 
190
- # free VAE cache between clips
191
  pipeline.vae.model.clear_cache()
192
 
193
- # Save only the first video
194
  if idx < num_prompts:
195
  model = "regular" if not use_ema else "ema"
196
  safe_name = prompt[:50].replace("/", "_").replace("\\", "_")
@@ -198,10 +189,10 @@ def reward_forcing_inference(
198
  write_video(output_path, video[0], fps=16)
199
  logs += f"Saved video: {output_path}\n"
200
 
201
- progress(1.0, desc="Done")
202
  return output_path, logs
203
 
204
- logs += "[WARN] No video generated in loop.\n"
205
  return None, logs
206
 
207
 
@@ -210,18 +201,15 @@ def gradio_generate(
210
  ):
211
  """
212
  Triggered by Gradio:
213
- - writes prompt to a temporary .txt file
214
- - runs reward_forcing_inference
215
  - returns video + logs
216
  """
217
  if not prompt or not prompt.strip():
218
- raise gr.Error("Please type a text prompt 🙂")
219
 
220
- # Duration -> number of latent timesteps
221
- if duration == "5s (21 frames)":
222
- num_output_frames = 21
223
- else:
224
- num_output_frames = 120
225
 
226
  os.makedirs(PROMPT_DIR, exist_ok=True)
227
 
@@ -239,34 +227,37 @@ def gradio_generate(
239
  )
240
 
241
  if video_path is None or not os.path.exists(video_path):
242
- raise gr.Error(
243
- "No video generated.\n"
244
- "Check the logs below for errors."
245
- )
246
 
247
  return video_path, logs
248
 
249
 
250
  # -------------------------------------------------------------------
251
- # Gradio UI
252
  # -------------------------------------------------------------------
253
 
254
- with gr.Blocks(title="Reward Forcing T2V Demo (inline inference)") as demo:
255
  gr.Markdown(
256
  """
257
- # 🎬 Reward Forcing Text-to-Video (inline)
258
 
259
- This version directly calls the inference logic in Python,
260
- allowing Gradio to track:
261
- - model initialization via `progress(...)`
262
- - video generation progress via `progress.tqdm(...)`
 
 
 
 
 
 
263
  """
264
  )
265
 
266
  with gr.Row():
267
  prompt_in = gr.Textbox(
268
  label="Prompt",
269
- placeholder="Ex: A cinematic shot of a spaceship flying above a neon city at night...",
270
  lines=4,
271
  )
272
 
@@ -282,11 +273,7 @@ with gr.Blocks(title="Reward Forcing T2V Demo (inline inference)") as demo:
282
 
283
  with gr.Row():
284
  video_out = gr.Video(label="Generated Video")
285
- logs_out = gr.Textbox(
286
- label="Logs",
287
- lines=12,
288
- interactive=False,
289
- )
290
 
291
  generate_btn.click(
292
  fn=gradio_generate,
@@ -295,5 +282,6 @@ with gr.Blocks(title="Reward Forcing T2V Demo (inline inference)") as demo:
295
  )
296
 
297
  demo.queue()
 
298
  if __name__ == "__main__":
299
  demo.launch()
 
18
  from utils.misc import set_seed
19
  from demo_utils.memory import get_cuda_free_memory_gb, DynamicSwapInstaller
20
 
21
+
22
  # -------------------------------------------------------------------
23
  # Download checkpoints once when the Space starts
24
  # -------------------------------------------------------------------
 
42
  local_dir="./checkpoints/Reward-Forcing-T2V-1.3B",
43
  )
44
 
45
+
46
  # === Paths ===
47
  CONFIG_PATH = "configs/reward_forcing.yaml"
48
  CHECKPOINT_PATH = "checkpoints/Reward-Forcing-T2V-1.3B/rewardforcing.pt"
 
65
  Inline / simplified version of inference.py:
66
  - single GPU
67
  - text-to-video only
68
+ - one .txt file = N prompts, but returns only the first generated video
69
  """
70
  logs = ""
71
 
 
79
 
80
  torch.set_grad_enabled(False)
81
 
82
+ # --------------------- Phase 1: model & config init ---------------------
83
  progress(0.05, desc="Init: loading config")
84
  logs += "Loading config...\n"
85
  config = OmegaConf.load(CONFIG_PATH)
 
89
  progress(0.15, desc="Init: creating pipeline")
90
  logs += "Creating pipeline...\n"
91
  if hasattr(config, "denoising_step_list"):
 
92
  pipeline = CausalInferencePipeline(config, device=device)
93
  else:
 
94
  pipeline = CausalDiffusionInferencePipeline(config, device=device)
95
 
96
  progress(0.35, desc="Init: loading checkpoint")
 
124
  dataset, batch_size=1, sampler=sampler, num_workers=0, drop_last=False
125
  )
126
 
127
+ # --------------------- Clean output folder ---------------------
128
  progress(0.7, desc="Cleaning output folder")
129
  output_folder = os.path.join(
130
  output_root, f"rewardforcing-{num_output_frames}f", checkpoint_step
 
133
  os.makedirs(output_folder, exist_ok=True)
134
  logs += f"Output directory: {output_folder}\n"
135
 
136
+ # --------------------- Phase 2: inference loop ---------------------
 
137
  for i, batch_data in progress.tqdm(
138
  enumerate(dataloader),
139
  total=num_prompts,
 
152
 
153
  all_video = []
154
 
155
+ # TEXT-TO-VIDEO only
156
  prompt = batch["prompts"][0]
157
  extended_prompt = batch.get("extended_prompts", [None])[0]
158
+ prompts = [extended_prompt] if extended_prompt else [prompt]
 
 
 
159
 
160
  initial_latent = None
161
 
 
162
  sampled_noise = torch.randn(
163
  [1, num_output_frames, 16, 60, 104],
164
  device=device,
 
167
 
168
  logs += f"Generating for prompt: {prompt[:80]}...\n"
169
 
170
+ # WAN2 inference
171
  video, latents = pipeline.inference(
172
  noise=sampled_noise,
173
  text_prompts=prompts,
 
178
 
179
  current_video = rearrange(video, "b t c h w -> b t h w c").cpu()
180
  all_video.append(current_video)
 
 
181
  video = 255.0 * torch.cat(all_video, dim=1)
182
 
 
183
  pipeline.vae.model.clear_cache()
184
 
 
185
  if idx < num_prompts:
186
  model = "regular" if not use_ema else "ema"
187
  safe_name = prompt[:50].replace("/", "_").replace("\\", "_")
 
189
  write_video(output_path, video[0], fps=16)
190
  logs += f"Saved video: {output_path}\n"
191
 
192
+ progress(1.0, desc="Done")
193
  return output_path, logs
194
 
195
+ logs += "[WARN] No video generated.\n"
196
  return None, logs
197
 
198
 
 
201
  ):
202
  """
203
  Triggered by Gradio:
204
+ - writes prompt to a .txt file
205
+ - performs inference
206
  - returns video + logs
207
  """
208
  if not prompt or not prompt.strip():
209
+ raise gr.Error("Please enter a text prompt 🙂")
210
 
211
+ # Duration number of frames
212
+ num_output_frames = 21 if duration == "5s (21 frames)" else 120
 
 
 
213
 
214
  os.makedirs(PROMPT_DIR, exist_ok=True)
215
 
 
227
  )
228
 
229
  if video_path is None or not os.path.exists(video_path):
230
+ raise gr.Error("No video generated. Check logs for details.")
 
 
 
231
 
232
  return video_path, logs
233
 
234
 
235
  # -------------------------------------------------------------------
236
+ # Gradio UI — updated title + intro text
237
  # -------------------------------------------------------------------
238
 
239
+ with gr.Blocks(title="Reward Forcing Text-to-Video Demo") as demo:
240
  gr.Markdown(
241
  """
242
+ # 🎬 Reward Forcing Text-to-Video Demo
243
 
244
+ Generate short videos from text prompts using a model trained with the **Reward Forcing** method.
245
+
246
+ Reward Forcing is a recent research technique that improves how well a video model follows a written description
247
+ by guiding training with learned reward signals. You can learn more here:
248
+ https://reward-forcing.github.io
249
+
250
+ 👉 Type a prompt, click **Generate**, and the video will appear below.
251
+ Longer and more detailed prompts usually produce better results.
252
+
253
+ > ⏳ The first run may take a little longer while the model loads — generation is faster afterwards.
254
  """
255
  )
256
 
257
  with gr.Row():
258
  prompt_in = gr.Textbox(
259
  label="Prompt",
260
+ placeholder="A cinematic shot of late-summer wheat fields moving in the wind...",
261
  lines=4,
262
  )
263
 
 
273
 
274
  with gr.Row():
275
  video_out = gr.Video(label="Generated Video")
276
+ logs_out = gr.Textbox(label="Logs", lines=12, interactive=False)
 
 
 
 
277
 
278
  generate_btn.click(
279
  fn=gradio_generate,
 
282
  )
283
 
284
  demo.queue()
285
+
286
  if __name__ == "__main__":
287
  demo.launch()