Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

commons.py 4.8 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
  1. import math
  2. import torch
  3. from torch.nn import functional as F
  4. import torch.jit
  5. def script_method(fn, _rcb=None):
  6. return fn
  7. def script(obj, optimize=True, _frames_up=0, _rcb=None):
  8. return obj
  9. torch.jit.script_method = script_method
  10. torch.jit.script = script
  11. def init_weights(m, mean=0.0, std=0.01):
  12. classname = m.__class__.__name__
  13. if classname.find("Conv") != -1:
  14. m.weight.data.normal_(mean, std)
  15. def get_padding(kernel_size, dilation=1):
  16. return int((kernel_size*dilation - dilation)/2)
  17. def convert_pad_shape(pad_shape):
  18. l = pad_shape[::-1]
  19. pad_shape = [item for sublist in l for item in sublist]
  20. return pad_shape
  21. def intersperse(lst, item):
  22. result = [item] * (len(lst) * 2 + 1)
  23. result[1::2] = lst
  24. return result
  25. def kl_divergence(m_p, logs_p, m_q, logs_q):
  26. """KL(P||Q)"""
  27. kl = (logs_q - logs_p) - 0.5
  28. kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
  29. return kl
  30. def rand_gumbel(shape):
  31. """Sample from the Gumbel distribution, protect from overflows."""
  32. uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
  33. return -torch.log(-torch.log(uniform_samples))
  34. def rand_gumbel_like(x):
  35. g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
  36. return g
  37. def slice_segments(x, ids_str, segment_size=4):
  38. ret = torch.zeros_like(x[:, :, :segment_size])
  39. for i in range(x.size(0)):
  40. idx_str = ids_str[i]
  41. idx_end = idx_str + segment_size
  42. ret[i] = x[i, :, idx_str:idx_end]
  43. return ret
  44. def rand_slice_segments(x, x_lengths=None, segment_size=4):
  45. b, d, t = x.size()
  46. if x_lengths is None:
  47. x_lengths = t
  48. ids_str_max = x_lengths - segment_size + 1
  49. ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
  50. ret = slice_segments(x, ids_str, segment_size)
  51. return ret, ids_str
  52. def get_timing_signal_1d(
  53. length, channels, min_timescale=1.0, max_timescale=1.0e4):
  54. position = torch.arange(length, dtype=torch.float)
  55. num_timescales = channels // 2
  56. log_timescale_increment = (
  57. math.log(float(max_timescale) / float(min_timescale)) /
  58. (num_timescales - 1))
  59. inv_timescales = min_timescale * torch.exp(
  60. torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)
  61. scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
  62. signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
  63. signal = F.pad(signal, [0, 0, 0, channels % 2])
  64. signal = signal.view(1, channels, length)
  65. return signal
  66. def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
  67. b, channels, length = x.size()
  68. signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
  69. return x + signal.to(dtype=x.dtype, device=x.device)
  70. def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
  71. b, channels, length = x.size()
  72. signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
  73. return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
  74. def subsequent_mask(length):
  75. mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
  76. return mask
  77. @torch.jit.script
  78. def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
  79. n_channels_int = n_channels[0]
  80. in_act = input_a + input_b
  81. t_act = torch.tanh(in_act[:, :n_channels_int, :])
  82. s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
  83. acts = t_act * s_act
  84. return acts
  85. def convert_pad_shape(pad_shape):
  86. l = pad_shape[::-1]
  87. pad_shape = [item for sublist in l for item in sublist]
  88. return pad_shape
  89. def shift_1d(x):
  90. x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
  91. return x
  92. def sequence_mask(length, max_length=None):
  93. if max_length is None:
  94. max_length = length.max()
  95. x = torch.arange(max_length, dtype=length.dtype, device=length.device)
  96. return x.unsqueeze(0) < length.unsqueeze(1)
  97. def generate_path(duration, mask):
  98. """
  99. duration: [b, 1, t_x]
  100. mask: [b, 1, t_y, t_x]
  101. """
  102. device = duration.device
  103. b, _, t_y, t_x = mask.shape
  104. cum_duration = torch.cumsum(duration, -1)
  105. cum_duration_flat = cum_duration.view(b * t_x)
  106. path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
  107. path = path.view(b, t_x, t_y)
  108. path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
  109. path = path.unsqueeze(1).transpose(2,3) * mask
  110. return path
  111. def clip_grad_value_(parameters, clip_value, norm_type=2):
  112. if isinstance(parameters, torch.Tensor):
  113. parameters = [parameters]
  114. parameters = list(filter(lambda p: p.grad is not None, parameters))
  115. norm_type = float(norm_type)
  116. if clip_value is not None:
  117. clip_value = float(clip_value)
  118. total_norm = 0
  119. for p in parameters:
  120. param_norm = p.grad.data.norm(norm_type)
  121. total_norm += param_norm.item() ** norm_type
  122. if clip_value is not None:
  123. p.grad.data.clamp_(min=-clip_value, max=clip_value)
  124. total_norm = total_norm ** (1. / norm_type)
  125. return total_norm
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...