Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
B
Basedformer
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Locked Files
Issues
0
Issues
0
List
Boards
Labels
Service Desk
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Security & Compliance
Security & Compliance
Dependency List
License Compliance
Packages
Packages
List
Container Registry
Analytics
Analytics
CI / CD
Code Review
Insights
Issues
Repository
Value Stream
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
novelai-storage
Basedformer
Commits
704947b4
Commit
704947b4
authored
Jul 13, 2022
by
Wes Brown
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Clean up, better reporting.
parent
cc02ad48
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
118 additions
and
124 deletions
+118
-124
basedformer/dataset.py
basedformer/dataset.py
+0
-1
hypertrain.py
hypertrain.py
+118
-123
No files found.
basedformer/dataset.py
View file @
704947b4
import
numpy
as
np
import
numpy
as
np
import
torch
import
torch
import
mmap
import
mmap
import
pickle
import
concurrent
import
concurrent
from
torch.utils
import
data
from
torch.utils
import
data
import
pickle
import
pickle
...
...
hypertrain.py
View file @
704947b4
from
re
import
A
import
torch
import
torch.nn
as
nn
import
torch.nn
as
nn
import
torch.nn.functional
as
F
import
torch.nn.functional
as
F
from
pathlib
import
Path
from
torch.utils
import
data
from
torch.utils
import
data
import
math
import
sys
from
tqdm
import
tqdm
import
time
import
wandb
import
wandb
import
numpy
as
np
from
torch.utils.checkpoint
import
checkpoint
as
ck
from
torch.utils.checkpoint
import
checkpoint
as
ck
from
math
import
log2
,
ceil
from
basedformer
import
optimizer
,
lm_utils
,
dataset
from
basedformer
import
optimizer
,
lm_utils
,
dataset
from
basedformer.utils
import
*
from
basedformer.utils
import
*
import
glob
from
transformers
import
AutoTokenizer
from
transformers
import
AutoTokenizer
from
basedformer
import
sampling
from
basedformer
import
sampling
from
icecream
import
ic
from
termcolor
import
colored
from
termcolor
import
colored
gpu
=
"cuda"
gpu
=
"cuda"
...
@@ -26,6 +15,9 @@ if gpu != "cuda":
...
@@ -26,6 +15,9 @@ if gpu != "cuda":
amp
=
torch
.
amp
amp
=
torch
.
amp
scaler
=
torch
.
cuda
.
amp
.
GradScaler
()
scaler
=
torch
.
cuda
.
amp
.
GradScaler
()
prompts
=
[
"<|endoftext|>"
]
def
_init_weights
(
module
):
def
_init_weights
(
module
):
if
isinstance
(
module
,
nn
.
Linear
):
if
isinstance
(
module
,
nn
.
Linear
):
module
.
weight
.
data
.
normal_
(
mean
=
0.0
,
std
=
0.02
)
module
.
weight
.
data
.
normal_
(
mean
=
0.0
,
std
=
0.02
)
...
@@ -39,49 +31,21 @@ def _init_weights(module):
...
@@ -39,49 +31,21 @@ def _init_weights(module):
module
.
bias
.
data
.
zero_
()
module
.
bias
.
data
.
zero_
()
module
.
weight
.
data
.
fill_
(
1.0
)
module
.
weight
.
data
.
fill_
(
1.0
)
def
shift_tokens
(
x
,
amt
,
eps
=
1e-5
):
n
,
device
=
x
.
shape
[
1
],
x
.
device
cumsum
=
x
.
cumsum
(
dim
=
1
)
*
x
,
x_pass
=
x
.
chunk
(
amt
+
1
,
dim
=
-
1
)
*
x_cumsum
,
_
=
cumsum
.
chunk
(
amt
+
1
,
dim
=
-
1
)
amts
=
2
**
torch
.
arange
(
amt
)
amts
=
amts
.
tolist
()
shifts
=
[]
denom
=
torch
.
arange
(
n
,
device
=
device
)
for
x_chunk
,
x_cumsum_chunk
,
amt
in
zip
(
x
,
x_cumsum
,
amts
):
shifted_chunk
=
shift
(
x_cumsum_chunk
,
amt
,
dim
=
-
2
)
-
shift
(
x_cumsum_chunk
,
2
*
amt
,
dim
=
-
2
)
shifted_denom
=
shift
(
denom
,
amt
,
dim
=
-
1
)
-
shift
(
denom
,
2
*
amt
,
dim
=
-
1
)
shifted_denom
=
rearrange
(
shifted_denom
,
'n -> () n ()'
)
normed_shifted_x
=
shifted_chunk
/
(
shifted_denom
+
eps
)
shifts
.
append
(
normed_shifted_x
)
return
torch
.
cat
((
*
shifts
,
x_pass
),
dim
=
-
1
)
def
discounted_cumsum
(
t
,
gamma
):
def
shift
(
x
,
amt
,
dim
=-
1
):
try
:
return
F
.
pad
(
x
,
(
*
((
0
,
0
)
*
(
-
dim
-
1
)),
amt
,
-
amt
),
value
=
0.
)
from
torch_discounted_cumsum
import
discounted_cumsum_left
except
ImportError
:
print
(
'unable to import torch_discounted_cumsum - please run `pip install torch-discounted-cumsum`'
)
b
,
n
,
d
=
t
.
shape
t
=
rearrange
(
t
,
'b n d -> (b d) n'
)
t
=
discounted_cumsum_left
(
t
,
gamma
)
t
=
rearrange
(
t
,
'(b d) n -> b n d'
,
b
=
b
)
return
t
def
shift
(
x
,
amt
,
dim
=
-
1
):
return
F
.
pad
(
x
,
(
*
((
0
,
0
)
*
(
-
dim
-
1
)),
amt
,
-
amt
),
value
=
0.
)
class
HyperNetworkGRU
(
nn
.
Module
):
class
HyperNetworkGRU
(
nn
.
Module
):
def
__init__
(
self
,
config
):
def
__init__
(
self
,
config
):
super
()
.
__init__
()
super
()
.
__init__
()
embed_dim
=
config
[
"hidden_dim"
]
embed_dim
=
config
[
"hidden_dim"
]
self
.
linear1
=
nn
.
Linear
(
embed_dim
,
embed_dim
//
8
)
self
.
linear1
=
nn
.
Linear
(
embed_dim
,
embed_dim
//
8
)
self
.
gru
=
nn
.
GRU
(
embed_dim
//
8
,
embed_dim
//
8
,
num_layers
=
1
,
bidirectional
=
False
,
batch_first
=
True
)
self
.
gru
=
nn
.
GRU
(
embed_dim
//
8
,
embed_dim
//
8
,
num_layers
=
1
,
bidirectional
=
False
,
batch_first
=
True
)
self
.
linear2
=
nn
.
Linear
(
embed_dim
//
8
,
embed_dim
)
self
.
linear2
=
nn
.
Linear
(
embed_dim
//
8
,
embed_dim
)
self
.
ln_1
=
nn
.
LayerNorm
(
embed_dim
//
8
,
eps
=
1e-5
)
self
.
ln_1
=
nn
.
LayerNorm
(
embed_dim
//
8
,
eps
=
1e-5
)
self
.
activation
=
gelu_new
self
.
activation
=
gelu_new
...
@@ -90,47 +54,42 @@ class HyperNetworkGRU(nn.Module):
...
@@ -90,47 +54,42 @@ class HyperNetworkGRU(nn.Module):
_init_weights
(
module
)
_init_weights
(
module
)
for
param
in
self
.
linear2
.
parameters
():
for
param
in
self
.
linear2
.
parameters
():
param
.
data
.
normal_
(
mean
=
0.0
,
std
=
(
0.02
/
math
.
sqrt
(
2
*
config
[
"n_layer"
])))
param
.
data
.
normal_
(
mean
=
0.0
,
std
=
(
0.02
/
math
.
sqrt
(
2
*
config
[
"n_layer"
])))
for
param
in
self
.
gru
.
parameters
():
for
param
in
self
.
gru
.
parameters
():
param
.
data
.
normal_
(
mean
=
0.0
,
std
=
(
0.02
/
math
.
sqrt
(
2
*
config
[
"n_layer"
])))
param
.
data
.
normal_
(
mean
=
0.0
,
std
=
(
0.02
/
math
.
sqrt
(
2
*
config
[
"n_layer"
])))
def
forward
(
self
,
x
):
def
forward
(
self
,
x
):
x
=
x
.
float
()
return
ck
(
self
.
activation
,
x
=
self
.
linear1
(
x
)
self
.
linear2
(
x
=
self
.
gru
(
x
)[
0
]
self
.
ln_1
(
x
=
self
.
ln_1
(
x
)
self
.
gru
(
x
=
self
.
linear2
(
x
)
self
.
linear1
(
x
=
ck
(
self
.
activation
,
x
)
x
.
float
()))[
0
])))
.
bfloat16
(
)
return
x
.
bfloat16
()
class
HyperNetwork
(
nn
.
Module
):
class
HyperNetwork
(
nn
.
Module
):
def
__init__
(
self
,
config
):
def
__init__
(
self
,
config
):
super
()
.
__init__
()
super
()
.
__init__
()
embed_dim
=
config
[
"hidden_dim"
]
embed_dim
=
config
[
"hidden_dim"
]
self
.
linear
=
nn
.
Linear
(
embed_dim
,
embed_dim
//
4
,
bias
=
True
)
self
.
linear
=
nn
.
Linear
(
embed_dim
,
embed_dim
//
4
,
bias
=
True
)
self
.
linear2
=
nn
.
Linear
(
embed_dim
//
4
,
embed_dim
,
bias
=
True
)
self
.
linear2
=
nn
.
Linear
(
embed_dim
//
4
,
embed_dim
,
bias
=
True
)
self
.
activation
=
torch
.
nn
.
functional
.
gelu
self
.
activation
=
torch
.
nn
.
functional
.
gelu
self
.
num_shifts
=
ceil
(
log2
(
2048
))
-
1
#self.linear.weight.data.normal_(mean=0.0, std=0.02)
for
module
in
self
.
modules
():
for
module
in
self
.
modules
():
_init_weights
(
module
)
_init_weights
(
module
)
for
param
in
self
.
linear2
.
parameters
():
for
param
in
self
.
linear2
.
parameters
():
param
.
data
.
normal_
(
mean
=
0.0
,
std
=
(
0.02
/
math
.
sqrt
(
2
*
config
[
"n_layer"
])))
param
.
data
.
normal_
(
mean
=
0.0
,
#state = self.state_dict()
std
=
(
0.02
/
math
.
sqrt
(
2
*
config
[
"n_layer"
])))
#for k in state:
# state[k] = state[k] * 1 / math.sqrt(2 * config["n_layer"])
#self.load_state_dict(state)
def
forward
(
self
,
x
):
def
forward
(
self
,
x
):
x
=
x
.
float
()
x
=
self
.
linear2
(
#x = shift_tokens(x, self.num_shifts)
ck
(
self
.
activation
,
x
=
self
.
linear
(
x
)
self
.
linear
(
x
.
float
())))
x
=
ck
(
self
.
activation
,
x
)
return
x
.
mul
(
torch
.
sigmoid
(
x
))
.
bfloat16
()
x
=
self
.
linear2
(
x
)
x
=
x
.
mul
(
torch
.
sigmoid
(
x
))
return
x
.
bfloat16
()
class
HyperNetworkSingle
(
nn
.
Module
):
class
HyperNetworkSingle
(
nn
.
Module
):
def
__init__
(
self
,
config
):
def
__init__
(
self
,
config
):
...
@@ -138,32 +97,30 @@ class HyperNetworkSingle(nn.Module):
...
@@ -138,32 +97,30 @@ class HyperNetworkSingle(nn.Module):
embed_dim
=
config
[
"hidden_dim"
]
embed_dim
=
config
[
"hidden_dim"
]
self
.
linear
=
nn
.
Linear
(
embed_dim
,
embed_dim
,
bias
=
True
)
self
.
linear
=
nn
.
Linear
(
embed_dim
,
embed_dim
,
bias
=
True
)
self
.
activation
=
gelu_new
self
.
activation
=
gelu_new
#self.linear.weight.data.normal_(mean=0.0, std=0.02)
#
self.linear.weight.data.normal_(mean=0.0, std=0.02)
for
module
in
self
.
modules
():
for
module
in
self
.
modules
():
_init_weights
(
module
)
_init_weights
(
module
)
for
param
in
self
.
linear
.
parameters
():
for
param
in
self
.
linear
.
parameters
():
param
.
data
.
normal_
(
mean
=
0.0
,
std
=
(
0.02
/
math
.
sqrt
(
2
*
config
[
"n_layer"
])))
param
.
data
.
normal_
(
mean
=
0.0
,
#state = self.state_dict()
std
=
(
0.02
/
math
.
sqrt
(
2
*
config
[
"n_layer"
])))
#for k in state:
# state = self.state_dict()
# for k in state:
# state[k] = state[k] * 1 / math.sqrt(2 * config["n_layer"])
# state[k] = state[k] * 1 / math.sqrt(2 * config["n_layer"])
#self.load_state_dict(state)
#
self.load_state_dict(state)
def
forward
(
self
,
x
):
def
forward
(
self
,
x
):
x
=
x
.
float
()
x
=
self
.
linear
(
x
.
float
())
#x = shift_tokens(x, self.num_shifts)
return
x
.
mul
(
torch
.
sigmoid
(
x
))
.
bfloat16
()
x
=
self
.
linear
(
x
)
x
=
x
.
mul
(
torch
.
sigmoid
(
x
))
return
x
.
bfloat16
()
tokenizer
=
AutoTokenizer
.
from_pretrained
(
'gpt2'
)
tokenizer
=
AutoTokenizer
.
from_pretrained
(
'gpt2'
)
@
torch
.
no_grad
()
@
torch
.
no_grad
()
def
sample
(
prompt
,
n_tokens
,
bsz
,
hypernetwork
=
None
):
def
sample
(
prompt
,
n_tokens
,
bsz
,
hypernetwork
=
None
,
step
=
0
):
torch
.
seed
()
torch
.
seed
()
tokens
=
tokenizer
.
encode
(
prompt
)
tokens
=
tokenizer
.
encode
(
prompt
)
#print("Prompt:")
#for x in range(len(tokens)):
# print(tokenizer.decode([tokens[x]]), end=" | ")
tokens
=
torch
.
LongTensor
(
tokens
)
.
unsqueeze
(
0
)
.
to
(
gpu
)
tokens
=
torch
.
LongTensor
(
tokens
)
.
unsqueeze
(
0
)
.
to
(
gpu
)
tokens
=
[
tokens
]
*
bsz
tokens
=
[
tokens
]
*
bsz
tokens
=
torch
.
cat
(
tokens
,
dim
=
0
)
tokens
=
torch
.
cat
(
tokens
,
dim
=
0
)
...
@@ -178,31 +135,52 @@ def sample(prompt, n_tokens, bsz, hypernetwork=None):
...
@@ -178,31 +135,52 @@ def sample(prompt, n_tokens, bsz, hypernetwork=None):
"temp"
:
0.8
,
"temp"
:
0.8
,
}
}
ops_list
=
[
ops
]
*
bsz
ops_list
=
[
ops
]
*
bsz
tokens_generated
=
sampling
.
generate
(
model
.
forward
,
tokens
,
n_tokens
,
ops_list
=
ops_list
,
hypernetwork
=
hypernetwork
,
non_deterministic
=
True
)
tokens_generated
=
sampling
.
generate
(
model
.
forward
,
vanilla_tokens_generated
=
sampling
.
generate
(
model
.
forward
,
tokens
,
n_tokens
,
ops_list
=
ops_list
,
hypernetwork
=
None
)
tokens
,
n_tokens
,
ops_list
=
ops_list
,
hypernetwork
=
hypernetwork
,
non_deterministic
=
True
)
vanilla_tokens_generated
=
sampling
.
generate
(
model
.
forward
,
tokens
,
n_tokens
,
ops_list
=
ops_list
,
hypernetwork
=
None
)
tokens_generated
=
tokenizer
.
batch_decode
(
tokens_generated
.
cpu
()
.
numpy
())
tokens_generated
=
tokenizer
.
batch_decode
(
tokens_generated
.
cpu
()
.
numpy
())
vanilla_tokens_generated
=
tokenizer
.
batch_decode
(
vanilla_tokens_generated
.
cpu
()
.
numpy
())
vanilla_tokens_generated
=
tokenizer
.
batch_decode
(
### send to wandb
vanilla_tokens_generated
.
cpu
()
.
numpy
())
columns
=
[
"Prompt"
,
"Generated Text"
,
"Vanilla Model"
]
data
=
[]
data
=
[]
for
x
in
range
(
len
(
tokens_generated
)):
for
x
in
range
(
len
(
tokens_generated
)):
data
.
append
([
prompt
,
str
(
tokens_generated
[
x
]),
str
(
vanilla_tokens_generated
[
x
])])
data
.
append
([
step
,
prompt
,
str
(
tokens_generated
[
x
]),
str
(
vanilla_tokens_generated
[
x
])])
for
gen
in
tokens_generated
:
return
data
print
(
colored
(
"=========================================================="
,
"red"
))
print
(
colored
(
gen
,
"green"
))
def
report_wandb
(
data
):
print
(
colored
(
"=========================================================="
,
"red"
))
columns
=
[
"Step"
,
"Prompt"
,
"Generated Text"
,
"Vanilla Model"
]
wandb
.
log
({
"Generations"
:
wandb
.
Table
(
data
=
data
,
columns
=
columns
)})
wandb
.
log
({
"Generations"
:
wandb
.
Table
(
data
=
data
,
columns
=
columns
)})
def
report_console
(
data
):
for
gen
in
data
[
3
]:
print
(
colored
(
"======================================================"
,
"red"
))
print
(
colored
(
gen
,
"green"
))
print
(
colored
(
"======================================================"
,
"red"
))
# we need 250 batch size to train the small GPT.
# we need 250 batch size to train the small GPT.
train_config
=
{
train_config
=
{
"data_path"
:
"dataset/
enwik9-gpt2-2049
.map"
,
"data_path"
:
"dataset/
cassandra
.map"
,
"save_path"
:
"models/
enwik9-sigurdv4
-hypernet2"
,
"save_path"
:
"models/
sigurdv4-cassandra
-hypernet2"
,
"lm_path"
:
"pretrained/sigurdv4"
,
"lm_path"
:
"pretrained/sigurdv4"
,
"optimizer"
:
"adamw"
,
"optimizer"
:
"adamw"
,
"masked_softmax_fusion"
:
False
,
"masked_softmax_fusion"
:
False
,
"do_save"
:
True
,
"do_save"
:
True
,
"run_name"
:
"
gptj-6b-enwik9
-6b-postln-bf16-2e-4-4bsz-every5layer"
,
"run_name"
:
"
sigurdv4-cassandra
-6b-postln-bf16-2e-4-4bsz-every5layer"
,
"lr"
:
2e-4
,
"lr"
:
2e-4
,
"end_lr"
:
2e-4
,
"end_lr"
:
2e-4
,
"warmup_steps"
:
50
,
"warmup_steps"
:
50
,
...
@@ -220,7 +198,6 @@ gas = train_config["gas"]
...
@@ -220,7 +198,6 @@ gas = train_config["gas"]
Path
(
train_config
[
"save_path"
])
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
Path
(
train_config
[
"save_path"
])
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
model
=
lm_utils
.
load_from_path
(
"pretrained/sigurdv4"
)
.
to
(
gpu
)
.
bfloat16
()
model
=
lm_utils
.
load_from_path
(
"pretrained/sigurdv4"
)
.
to
(
gpu
)
.
bfloat16
()
for
param
in
model
.
parameters
():
for
param
in
model
.
parameters
():
param
.
requires_grad
=
False
param
.
requires_grad
=
False
...
@@ -233,26 +210,37 @@ hypernetwork = HyperNetworkSingle(model.config).to(gpu).float()
...
@@ -233,26 +210,37 @@ hypernetwork = HyperNetworkSingle(model.config).to(gpu).float()
for
param
in
hypernetwork
.
parameters
():
for
param
in
hypernetwork
.
parameters
():
param
.
requires_grad
=
True
param
.
requires_grad
=
True
cp_list
=
sorted
(
os
.
listdir
(
train_config
[
"save_path"
]),
key
=
lambda
x
:
int
(
x
.
split
(
"_"
)[
-
1
]))
cp_list
=
sorted
(
os
.
listdir
(
train_config
[
"save_path"
]),
last_cp
=
Path
(
train_config
[
"save_path"
])
/
cp_list
[
-
1
]
if
len
(
cp_list
)
>
0
else
None
key
=
lambda
x
:
int
(
x
.
split
(
"_"
)[
-
1
]))
last_cp
=
Path
(
train_config
[
"save_path"
])
/
cp_list
[
-
1
]
if
len
(
cp_list
)
>
0
else
None
print
(
last_cp
)
print
(
last_cp
)
if
last_cp
:
if
last_cp
:
print
(
"Loading from step {}"
.
format
(
cp_list
[
-
1
]
.
split
(
"_"
)[
-
1
]))
print
(
"Loading from step {}"
.
format
(
cp_list
[
-
1
]
.
split
(
"_"
)[
-
1
]))
hypernetwork
.
load_state_dict
(
torch
.
load
(
last_cp
/
"hyper.pt"
))
hypernetwork
.
load_state_dict
(
torch
.
load
(
last_cp
/
"hyper.pt"
))
opt
=
optimizer
.
BasedOptimizer
.
load
(
hypernetwork
.
parameters
(),
last_cp
/
"opt"
)
opt
=
optimizer
.
BasedOptimizer
.
load
(
hypernetwork
.
parameters
(),
last_cp
/
"opt"
)
else
:
else
:
opt
=
optimizer
.
BasedOptimizer
(
hypernetwork
.
parameters
(),
train_config
,
train_config
[
"optimizer"
])
opt
=
optimizer
.
BasedOptimizer
(
hypernetwork
.
parameters
(),
train_config
,
train_config
[
"optimizer"
])
# TODO: Add load, add evals, add FP16 AMP, and Data Parallel, outputting hidden states from the get_logits function.
# TODO: Add load, add evals, add FP16 AMP, and Data Parallel, outputting hidden
# states from the get_logits function.
print
(
opt
.
curr_step
)
print
(
opt
.
curr_step
)
train_dataset
=
dataset
.
ShardedDataset
(
2049
,
train_config
[
"data_path"
])
train_dataset
=
dataset
.
ShardedDataset
(
2049
,
train_config
[
"data_path"
])
if
last_cp
:
if
last_cp
:
train_dataset
.
skip
=
opt
.
curr_step
*
bs
*
gas
train_dataset
.
skip
=
opt
.
curr_step
*
bs
*
gas
train_loader
=
data
.
DataLoader
(
train_dataset
,
batch_size
=
bs
*
gas
,
shuffle
=
False
,
num_workers
=
0
,
)
train_loader
=
data
.
DataLoader
(
train_dataset
,
wandb
.
init
(
project
=
"hypernetwork-tests"
,
name
=
train_config
[
"run_name"
],
config
=
{
**
train_config
,
**
model
.
config
})
batch_size
=
bs
*
gas
,
shuffle
=
False
,
num_workers
=
0
)
wandb
.
init
(
project
=
"hypernetwork-tests"
,
name
=
train_config
[
"run_name"
],
config
=
{
**
train_config
,
**
model
.
config
})
if
last_cp
:
if
last_cp
:
curr_step
=
opt
.
curr_step
curr_step
=
opt
.
curr_step
...
@@ -260,21 +248,22 @@ else:
...
@@ -260,21 +248,22 @@ else:
curr_step
=
0
curr_step
=
0
t
=
tqdm
(
train_loader
,
initial
=
curr_step
)
t
=
tqdm
(
train_loader
,
initial
=
curr_step
)
sample_data
=
[]
#sample("<|endoftext|>", 500, 3, hypernetwork=hypernetwork)
for
input_ids
,
labels
in
t
:
for
input_ids
,
labels
in
t
:
timex
=
time
.
perf_counter
()
timex
=
time
.
perf_counter
()
input_ids
=
input_ids
.
to
(
gpu
)
input_ids
=
input_ids
.
to
(
gpu
)
labels
=
labels
.
to
(
gpu
)
labels
=
labels
.
to
(
gpu
)
loss
=
0
loss
=
0
for
x
in
range
(
train_config
[
"gas"
]):
for
x
in
range
(
train_config
[
"gas"
]):
with
amp
.
autocast
(
enabled
=
train_config
[
"amp"
],
dtype
=
torch
.
float16
):
with
amp
.
autocast
(
enabled
=
train_config
[
"amp"
],
logits
,
_
=
model
(
input_ids
[
x
*
bs
:(
x
+
1
)
*
bs
,
:]
.
to
(
gpu
),
hypernetwork
=
hypernetwork
,
act_ck
=
True
)
dtype
=
torch
.
float16
):
#print(tokenizer.decode(input_ids[x*bs:(x+1)*bs, :][0]))
logits
,
_
=
model
(
input_ids
[
x
*
bs
:(
x
+
1
)
*
bs
,
:]
.
to
(
gpu
),
hypernetwork
=
hypernetwork
,
act_ck
=
True
)
# print(tokenizer.decode(input_ids[x*bs:(x+1)*bs, :][0]))
logits
=
logits
.
view
(
-
1
,
logits
.
shape
[
-
1
])
logits
=
logits
.
view
(
-
1
,
logits
.
shape
[
-
1
])
gas_labels
=
labels
[
x
*
bs
:(
x
+
1
)
*
bs
,
:]
.
contiguous
()
gas_labels
=
labels
[
x
*
bs
:(
x
+
1
)
*
bs
,
:]
.
contiguous
()
gas_labels
=
gas_labels
.
view
(
-
1
)
gas_labels
=
gas_labels
.
view
(
-
1
)
gas_loss
=
F
.
cross_entropy
(
logits
,
gas_labels
)
gas_loss
=
F
.
cross_entropy
(
logits
,
gas_labels
)
...
@@ -301,27 +290,33 @@ for input_ids, labels in t:
...
@@ -301,27 +290,33 @@ for input_ids, labels in t:
sec_per_step
=
(
time
.
perf_counter
()
-
timex
)
sec_per_step
=
(
time
.
perf_counter
()
-
timex
)
step_per_sec
=
(
1.
/
sec_per_step
)
step_per_sec
=
(
1.
/
sec_per_step
)
tokens_per_sec
=
(
step_per_sec
*
2048
)
*
bs
*
gas
tokens_per_sec
=
(
step_per_sec
*
2048
)
*
bs
*
gas
t
.
set_description
(
f
"{step_per_sec:.2f} steps/s, {sec_per_step:.2f}s/step, {tokens_per_sec:.2f}tokens/s, loss={loss:.4f}"
)
t
.
set_description
(
f
"{step_per_sec:.2f} steps/s, {sec_per_step:.2f}s/step,"
+
f
"{tokens_per_sec:.2f}tokens/s, loss={loss:.4f}"
)
wandb
.
log
(
wandb
.
log
(
{
{
"train/loss"
:
loss
,
"train/loss"
:
loss
,
"train/tokens_per_sec"
:
tokens_per_sec
,
"train/tokens_per_sec"
:
tokens_per_sec
,
"train/sec_per_step"
:
sec_per_step
,
"train/sec_per_step"
:
sec_per_step
,
"train/step_per_sec"
:
step_per_sec
,
"train/step_per_sec"
:
step_per_sec
,
"train/lr"
:
opt
.
curr_lr
,
"train/lr"
:
opt
.
curr_lr
,
"train/loss_scale"
:
scaler
.
get_scale
()
"train/loss_scale"
:
scaler
.
get_scale
()
},
},
step
=
curr_step
)
step
=
curr_step
)
if
train_config
[
"do_save"
]
and
curr_step
%
train_config
[
"save_every"
]
==
0
and
curr_step
!=
0
:
if
train_config
[
"do_save"
]
and
curr_step
%
train_config
[
"save_every"
]
==
0
and
curr_step
!=
0
:
save_folder
=
Path
(
train_config
[
"save_path"
])
/
f
"step_{curr_step}"
save_folder
=
Path
(
train_config
[
"save_path"
])
/
f
"step_{curr_step}"
save_folder
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
save_folder
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
torch
.
save
(
hypernetwork
.
state_dict
(),
save_folder
/
"hyper.pt"
)
torch
.
save
(
hypernetwork
.
state_dict
(),
save_folder
/
"hyper.pt"
)
opt
.
save
(
save_folder
/
"opt"
)
opt
.
save
(
save_folder
/
"opt"
)
print
(
f
"Saved model at step {curr_step}"
)
print
(
f
"
\n
Saved model at step {curr_step}"
)
if
curr_step
%
train_config
[
"eval_every"
]
==
0
and
curr_step
!=
0
:
if
curr_step
%
train_config
[
"eval_every"
]
==
0
and
curr_step
!=
0
:
print
(
""
)
for
prompt
in
prompts
:
sample
(
"<|endoftext|>"
,
500
,
3
,
hypernetwork
=
hypernetwork
)
sampled
=
sample
(
prompt
,
500
,
3
,
hypernetwork
=
hypernetwork
)
print
(
f
"PROMPT:
\n
{prompt}"
)
report_console
(
sampled
)
sample_data
=
sample_data
+
sampled
report_wandb
(
sample_data
)
curr_step
+=
1
curr_step
+=
1
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment