manbeast3b commited on
Commit
a3dcbb5
·
verified ·
1 Parent(s): e59907a

Update src/pipeline.py

Browse files
Files changed (1) hide show
  1. src/pipeline.py +13 -31
src/pipeline.py CHANGED
@@ -13,7 +13,6 @@ import numpy as np
13
  import os
14
  import pickle
15
  from tqdm import tqdm
16
- import math
17
 
18
  import torchvision.models as models
19
  import torch.nn.functional as F
@@ -69,39 +68,22 @@ class LossSchedulerModel(torch.nn.Module):
69
 
70
  return result #.to(xT.dtype)
71
 
72
-
73
-
74
-
75
  class LossSchedulerModel(torch.nn.Module):
76
- def __init__(A,wx=None,we=None,wb=None, timesteps=13, input_shape=[13, 13]):
77
  super(LossSchedulerModel,A).__init__()
78
- if wx is None:
79
- A.register_parameter('wx',torch.nn.Parameter(A.init1d(timesteps)))
80
- else:
81
- A.register_parameter('wx',torch.nn.Parameter(wx))
82
- if wb is None:
83
- A.register_parameter('we',torch.nn.Parameter(A.init2d(A.wx.shape[0], A.wx.shape[0])))
84
- else:
85
- A.register_parameter('we',torch.nn.Parameter(we))
86
- if wb is None:
87
- A.register_parameter('wb',torch.nn.Parameter(A.init1d(A.wx.shape[0])))
88
- else:
89
- A.register_parameter('wb',torch.nn.Parameter(wb))
90
  assert len(wx.shape)==1 and len(we.shape)==2;B=wx.shape[0];assert B==we.shape[0]and B==we.shape[1]
 
 
 
 
 
 
91
 
92
  def forward(A,t,xT,e_prev):
93
  B=e_prev;assert t-len(B)+1==0;C=xT*A.wx[t]
94
  for(D,E)in zip(B,A.we[t]):C+=D*E
95
  C += A.wb[t]
96
  return C.to(xT.dtype)
97
-
98
- def init1d(A, point):
99
- stdv = 1. / math.sqrt(point)
100
- return torch.empty(point).uniform_(-stdv, stdv)
101
-
102
- def init2d(A, rows, cols):
103
- stdv = 1. / math.sqrt(rows)
104
- return torch.empty(rows, cols).uniform_(-stdv, stdv)
105
 
106
  class LossScheduler:
107
  def __init__(A,timesteps,model):A.timesteps=timesteps;A.model=model;A.init_noise_sigma=1.;A.order=1
@@ -363,7 +345,7 @@ def load_pipeline(pipeline=None) -> StableDiffusionXLPipeline:
363
  alpha = 0.60
364
  # loss_fn = PerceptualLoss()
365
  # Training loop
366
- num_epochs = 2500
367
 
368
  for epoch in range(num_epochs):
369
  total_loss = 0
@@ -425,19 +407,19 @@ def load_pipeline(pipeline=None) -> StableDiffusionXLPipeline:
425
  timesteps_sel = torch.tensor(timesteps_sel)
426
  # scheduler = LossScheduler(timesteps=timesteps_sel, model=loss_model)
427
  # scheduler.save(f'../optimized_loss_params_{name}.pth')
428
- torch.save(pipeline.scheduler.loss_model.state_dict(), f'../large_loss_params_{name}.pth')
429
  print("model saved")
430
 
431
  # Update the pipeline with the new parameters
432
  # pipeline.scheduler = SchedulerWrapper(DDIMScheduler.from_config(orig_scheduler.config))
433
  # pipeline.scheduler.load_loss_params_path(f'../optimized_loss_params_{name}.pth') # Reload the updated parameters
434
- model = LossSchedulerModel(input_shape=(1, 4, 128, 128))
435
- model.load_state_dict(torch.load(f'../large_loss_params_{name}.pth', map_location=torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')))
436
  model.eval()
437
  pipeline.scheduler.loss_scheduler.model = model
438
  pipeline.scheduler.loss_model = model
439
  output_images = pipeline(prompts[0], output_type="pil", num_inference_steps=len(selected_indices), generator=generator, guidance_scale=5.0).images
440
- output_images[0].save(f"../large_final_image_{name}.png")
441
 
442
  # # import pdb; pdb.set_trace()
443
  # simialrity = torch.nn.CosineSimilarity(dim=1)(output_images[0].flatten(1), target_images[0].flatten(1)).mean()
@@ -466,4 +448,4 @@ def infer(request: TextToImageRequest, pipeline: StableDiffusionXLPipeline) -> I
466
  guidance_rescale = 0.0,
467
  callback_on_step_end=callback_dynamic_cfg,
468
  callback_on_step_end_tensor_inputs=['prompt_embeds', 'add_text_embeds', 'add_time_ids'],
469
- ).images[0]
 
13
  import os
14
  import pickle
15
  from tqdm import tqdm
 
16
 
17
  import torchvision.models as models
18
  import torch.nn.functional as F
 
68
 
69
  return result #.to(xT.dtype)
70
 
 
 
 
71
  class LossSchedulerModel(torch.nn.Module):
72
+ def __init__(A,wx,we,wb=None):
73
  super(LossSchedulerModel,A).__init__()
 
 
 
 
 
 
 
 
 
 
 
 
74
  assert len(wx.shape)==1 and len(we.shape)==2;B=wx.shape[0];assert B==we.shape[0]and B==we.shape[1]
75
+ A.register_parameter('wx',torch.nn.Parameter(wx))
76
+ A.register_parameter('we',torch.nn.Parameter(we))
77
+ if wb is None:
78
+ A.register_parameter('wb',torch.nn.Parameter(torch.randn(wx.shape)))
79
+ else:
80
+ A.register_parameter('wb',torch.nn.Parameter(wb)
81
 
82
  def forward(A,t,xT,e_prev):
83
  B=e_prev;assert t-len(B)+1==0;C=xT*A.wx[t]
84
  for(D,E)in zip(B,A.we[t]):C+=D*E
85
  C += A.wb[t]
86
  return C.to(xT.dtype)
 
 
 
 
 
 
 
 
87
 
88
  class LossScheduler:
89
  def __init__(A,timesteps,model):A.timesteps=timesteps;A.model=model;A.init_noise_sigma=1.;A.order=1
 
345
  alpha = 0.60
346
  # loss_fn = PerceptualLoss()
347
  # Training loop
348
+ num_epochs = 2000
349
 
350
  for epoch in range(num_epochs):
351
  total_loss = 0
 
407
  timesteps_sel = torch.tensor(timesteps_sel)
408
  # scheduler = LossScheduler(timesteps=timesteps_sel, model=loss_model)
409
  # scheduler.save(f'../optimized_loss_params_{name}.pth')
410
+ torch.save(pipeline.scheduler.loss_model.state_dict(), f'../large_12_loss_params_{name}.pth')
411
  print("model saved")
412
 
413
  # Update the pipeline with the new parameters
414
  # pipeline.scheduler = SchedulerWrapper(DDIMScheduler.from_config(orig_scheduler.config))
415
  # pipeline.scheduler.load_loss_params_path(f'../optimized_loss_params_{name}.pth') # Reload the updated parameters
416
+ model = LossSchedulerModel(pipeline.scheduler.loss_model.wx, pipeline.scheduler.loss_model.we) #input_shape=(1, 4, 128, 128)
417
+ model.load_state_dict(torch.load(f'../large_12_loss_params_{name}.pth', map_location=torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')))
418
  model.eval()
419
  pipeline.scheduler.loss_scheduler.model = model
420
  pipeline.scheduler.loss_model = model
421
  output_images = pipeline(prompts[0], output_type="pil", num_inference_steps=len(selected_indices), generator=generator, guidance_scale=5.0).images
422
+ output_images[0].save(f"../large_12_final_image_{name}.png")
423
 
424
  # # import pdb; pdb.set_trace()
425
  # simialrity = torch.nn.CosineSimilarity(dim=1)(output_images[0].flatten(1), target_images[0].flatten(1)).mean()
 
448
  guidance_rescale = 0.0,
449
  callback_on_step_end=callback_dynamic_cfg,
450
  callback_on_step_end_tensor_inputs=['prompt_embeds', 'add_text_embeds', 'add_time_ids'],
451
+ ).images[0]