util.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import importlib
  2. import torch
  3. import numpy as np
  4. from inspect import isfunction
  5. from PIL import Image, ImageDraw, ImageFont
  6. def log_txt_as_img(wh, xc, size=10):
  7. # wh a tuple of (width, height)
  8. # xc a list of captions to plot
  9. b = len(xc)
  10. txts = list()
  11. for bi in range(b):
  12. txt = Image.new("RGB", wh, color="white")
  13. draw = ImageDraw.Draw(txt)
  14. font = ImageFont.truetype('data/DejaVuSans.ttf', size=size)
  15. nc = int(40 * (wh[0] / 256))
  16. lines = "\n".join(xc[bi][start:start + nc] for start in range(0, len(xc[bi]), nc))
  17. try:
  18. draw.text((0, 0), lines, fill="black", font=font)
  19. except UnicodeEncodeError:
  20. print("Cant encode string for logging. Skipping.")
  21. txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0
  22. txts.append(txt)
  23. txts = np.stack(txts)
  24. txts = torch.tensor(txts)
  25. return txts
  26. def ismap(x):
  27. if not isinstance(x, torch.Tensor):
  28. return False
  29. return (len(x.shape) == 4) and (x.shape[1] > 3)
  30. def isimage(x):
  31. if not isinstance(x,torch.Tensor):
  32. return False
  33. return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
  34. def exists(x):
  35. return x is not None
  36. def default(val, d):
  37. if exists(val):
  38. return val
  39. return d() if isfunction(d) else d
  40. def mean_flat(tensor):
  41. """
  42. https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86
  43. Take the mean over all non-batch dimensions.
  44. """
  45. return tensor.mean(dim=list(range(1, len(tensor.shape))))
  46. def count_params(model, verbose=False):
  47. total_params = sum(p.numel() for p in model.parameters())
  48. if verbose:
  49. print(f"{model.__class__.__name__} has {total_params*1.e-6:.2f} M params.")
  50. return total_params
  51. def instantiate_from_config(config):
  52. if not "target" in config:
  53. if config == '__is_first_stage__':
  54. return None
  55. elif config == "__is_unconditional__":
  56. return None
  57. raise KeyError("Expected key `target` to instantiate.")
  58. return get_obj_from_str(config["target"])(**config.get("params", dict()))
  59. def get_obj_from_str(string, reload=False):
  60. module, cls = string.rsplit(".", 1)
  61. if reload:
  62. module_imp = importlib.import_module(module)
  63. importlib.reload(module_imp)
  64. return getattr(importlib.import_module(module, package=None), cls)