You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

_utils.py 4.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """
  2. Copyright 2020 Tianshu AI Platform. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. =============================================================
  13. """
  14. import numpy as np
  15. import math
  16. import torch
  17. import random
  18. from copy import deepcopy
  19. import contextlib, hashlib
  20. def split_batch(batch):
  21. if isinstance(batch, (list, tuple)):
  22. inputs, *targets = batch
  23. if len(targets)==1:
  24. targets = targets[0]
  25. return inputs, targets
  26. else:
  27. return [batch, None]
  28. @contextlib.contextmanager
  29. def set_mode(model, training=True):
  30. ori_mode = model.training
  31. model.train(training)
  32. yield
  33. model.train(ori_mode)
  34. def move_to_device(obj, device):
  35. if isinstance(obj, torch.Tensor):
  36. return obj.to(device=device)
  37. elif isinstance( obj, (list, tuple) ):
  38. return [ o.to(device=device) for o in obj ]
  39. elif isinstance(obj, nn.Module):
  40. return obj.to(device=device)
  41. def pack_images(images, col=None, channel_last=False):
  42. # N, C, H, W
  43. if isinstance(images, (list, tuple) ):
  44. images = np.stack(images, 0)
  45. if channel_last:
  46. images = images.transpose(0,3,1,2) # make it channel first
  47. assert len(images.shape)==4
  48. assert isinstance(images, np.ndarray)
  49. N,C,H,W = images.shape
  50. if col is None:
  51. col = int(math.ceil(math.sqrt(N)))
  52. row = int(math.ceil(N / col))
  53. pack = np.zeros( (C, H*row, W*col), dtype=images.dtype )
  54. for idx, img in enumerate(images):
  55. h = (idx//col) * H
  56. w = (idx% col) * W
  57. pack[:, h:h+H, w:w+W] = img
  58. return pack
  59. def normalize(tensor, mean, std, reverse=False):
  60. if reverse:
  61. _mean = [ -m / s for m, s in zip(mean, std) ]
  62. _std = [ 1/s for s in std ]
  63. else:
  64. _mean = mean
  65. _std = std
  66. _mean = torch.as_tensor(_mean, dtype=tensor.dtype, device=tensor.device)
  67. _std = torch.as_tensor(_std, dtype=tensor.dtype, device=tensor.device)
  68. tensor = (tensor - _mean[None, :, None, None]) / (_std[None, :, None, None])
  69. return tensor
  70. class Normalizer(object):
  71. def __init__(self, mean, std, reverse=False):
  72. self.mean = mean
  73. self.std = std
  74. self.reverse = reverse
  75. def __call__(self, x):
  76. if self.reverse:
  77. return self.denormalize(x)
  78. else:
  79. return self.normalize(x)
  80. def normalize(self, x):
  81. return normalize( x, self.mean, self.std )
  82. def denormalize(self, x):
  83. return normalize( x, self.mean, self.std, reverse=True )
  84. def colormap(N=256, normalized=False):
  85. def bitget(byteval, idx):
  86. return ((byteval & (1 << idx)) != 0)
  87. dtype = 'float32' if normalized else 'uint8'
  88. cmap = np.zeros((N, 3), dtype=dtype)
  89. for i in range(N):
  90. r = g = b = 0
  91. c = i
  92. for j in range(8):
  93. r = r | (bitget(c, 0) << 7-j)
  94. g = g | (bitget(c, 1) << 7-j)
  95. b = b | (bitget(c, 2) << 7-j)
  96. c = c >> 3
  97. cmap[i] = np.array([r, g, b])
  98. cmap = cmap/255 if normalized else cmap
  99. return cmap
  100. DEFAULT_COLORMAP = colormap()
  101. def flatten_dict(dic):
  102. flattned = dict()
  103. def _flatten(prefix, d):
  104. for k, v in d.items():
  105. if isinstance(v, dict):
  106. if prefix is None:
  107. _flatten( k, v )
  108. else:
  109. _flatten( prefix+'%s/'%k, v )
  110. else:
  111. flattned[ (prefix+'%s/'%k).strip('/') ] = v
  112. _flatten('', dic)
  113. return flattned
  114. def setup_seed(seed):
  115. torch.manual_seed(seed)
  116. torch.cuda.manual_seed(seed)
  117. np.random.seed(seed)
  118. random.seed(seed)
  119. def count_parameters(model):
  120. return sum( [ p.numel() for p in model.parameters() ] )
  121. def md5(fname):
  122. hash_md5 = hashlib.md5()
  123. with open(fname, "rb") as f:
  124. for chunk in iter(lambda: f.read(4096), b""):
  125. hash_md5.update(chunk)
  126. return hash_md5.hexdigest()

一站式算法开发平台、高性能分布式深度学习框架、先进算法模型库、视觉模型炼知平台、数据可视化分析平台等一系列平台及工具,在模型高效分布式训练、数据处理和可视分析、模型炼知和轻量化等技术上形成独特优势,目前已在产学研等各领域近千家单位及个人提供AI应用赋能