Kaggle competition: Gendered Pronoun Resolution
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<define_variables>
!wget https://github.com/google-research-datasets/gap-coreference/raw/master/gap-development.tsv -q
!wget https://github.com/google-research-datasets/gap-coreference/raw/master/gap-test.tsv -q
!wget https://github.com/google-research-datasets/gap-coreference/raw/master/gap-validation.tsv -q
GCS_DS_PATH = KaggleDatasets().get_gcs_path()<define_variables>
!pip install pytorch-pretrained-bert
!pip install https://github.com/ceshine/pytorch_helper_bot/archive/0.0.4.zip
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec' )<define_variables>
os.environ["SEED"] = "2524"
SKIP_VALIDATION = False
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES<define_variables>
BERT_MODEL = 'bert-large-uncased'
CASED = False
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']<normalization>
def insert_tag(row):

 to_be_inserted = sorted([ 
(row["A-offset"], " [A] "), 
(row["B-offset"], " [B] "), 
(row["Pronoun-offset"], " [P] ")
 ], key=lambda x: x[0], reverse=True)
 text = row["Text"]
for offset, tag in to_be_inserted:
text = text[:offset] + tag + text[offset:]
return text
def tokenize(text, tokenizer):

 entries = {}
final_tokens = []
for token in tokenizer.tokenize(text):
if token in("[A]", "[B]", "[P]"):
entries[token] = len(final_tokens)
 continue
final_tokens.append(token)
 return final_tokens,(entries["[A]"], entries["[B]"], entries["[P]"])
 class GAPDataset(Dataset):

 def __init__(self, df, tokenizer, labeled=True):
self.labeled = labeled
if labeled:
tmp = df[["A-coref", "B-coref"]].copy()
tmp["Neither"] = ~(df["A-coref"] | df["B-coref"])
 self.y = tmp.values.astype("bool")
 self.offsets, self.tokens = [], []
for _, row in df.iterrows() :
text = insert_tag(row)
 tokens, offsets = tokenize(text, tokenizer)
 self.offsets.append(offsets)
 self.tokens.append(tokenizer.convert_tokens_to_ids(
 ["[CLS]"] + tokens + ["[SEP]"]))
def __len__(self):
return len(self.tokens)
 def __getitem__(self, idx):
if self.labeled:
return self.tokens[idx], self.offsets[idx], self.y[idx]
return self.tokens[idx], self.offsets[idx]
def collate_examples(batch, truncate_len=500):

 transposed = list(zip(*batch))
max_len = min(
 max(( len(x)for x in transposed[0])) ,
truncate_len 
)
 tokens = np.zeros(( len(batch), max_len), dtype=np.int64)
 for i, row in enumerate(transposed[0]):
row = np.array(row[:truncate_len])
 tokens[i, :len(row)] = row
token_tensor = torch.from_numpy(tokens)
 offsets = torch.stack([
torch.LongTensor(x)for x in transposed[1]
], dim=0)+ 1
if len(transposed)== 2:
return token_tensor, offsets, None
one_hot_labels = torch.stack([
torch.from_numpy(x.astype("uint8")) for x in transposed[2]
], dim=0)
 _, labels = one_hot_labels.max(dim=1)
 return token_tensor, offsets, labels
def collate_examples_no_labels(batch, truncate_len=500):

 transposed = list(zip(*batch))
print("transposed size is", transposed.size())
 max_len = min(
 max(( len(x)for x in transposed[0])) ,
truncate_len 
)
 tokens = np.zeros(( len(batch), max_len), dtype=np.int64)
 for i, row in enumerate(transposed[0]):
row = np.array(row[:truncate_len])
 tokens[i, :len(row)] = row
token_tensor = torch.from_numpy(tokens)
 offsets = torch.stack([
torch.LongTensor(x)for x in transposed[1]
], dim=0)+ 1
if len(transposed)== 2:
return token_tensor, offsets, None
one_hot_labels = torch.stack([
torch.from_numpy(x.astype("uint8")) for x in transposed[2]
], dim=0)
 _, labels = one_hot_labels.max(dim=1)
 return token_tensor, offsets, labels
class Head(nn.Module):

 def __init__(self, bert_hidden_size: int):
super().__init__()
self.head_hidden_size = 1024
self.bert_hidden_size = bert_hidden_size
self.fc = nn.Sequential(
 nn.BatchNorm1d(bert_hidden_size * 3),
nn.Dropout(0.2),
nn.Linear(bert_hidden_size * 3, self.head_hidden_size),
nn.ReLU() ,
nn.BatchNorm1d(self.head_hidden_size),
nn.Dropout(0.2),
nn.Linear(self.head_hidden_size, self.head_hidden_size),
nn.ReLU() ,
nn.BatchNorm1d(self.head_hidden_size),
nn.Dropout(0.3),
nn.Linear(self.head_hidden_size, self.head_hidden_size),
nn.ReLU() ,
nn.BatchNorm1d(self.head_hidden_size),
nn.Dropout(0.5),
nn.Linear(self.head_hidden_size, 3)
)
 for i, module in enumerate(self.fc):
if isinstance(module,(nn.BatchNorm1d, nn.BatchNorm2d)) :
nn.init.constant_(module.weight, 1)
 nn.init.constant_(module.bias, 0)
 print("Initing batchnorm")
 elif isinstance(module, nn.Linear):
if getattr(module, "weight_v", None)is not None:
nn.init.uniform_(module.weight_g, 0, 1)
 nn.init.kaiming_normal_(module.weight_v)
 print("Initing linear with weight normalization")
 assert model[i].weight_g is not None
else:
nn.init.kaiming_normal_(module.weight)
 print("Initing linear")
 nn.init.constant_(module.bias, 0)
 def forward(self, bert_outputs, offsets):
assert bert_outputs.size(2)== self.bert_hidden_size
extracted_outputs = bert_outputs.gather(
 1, offsets.unsqueeze(2 ).expand(-1, -1, bert_outputs.size(2))
).view(bert_outputs.size(0), -1)
 return self.fc(extracted_outputs)
 class GAPModel(nn.Module):

 def __init__(self, bert_model: str, device: torch.device):
super().__init__()
self.device = device
if bert_model in("bert-base-uncased", "bert-base-cased"):
self.bert_hidden_size = 768
elif bert_model in("bert-large-uncased", "bert-large-cased"):
self.bert_hidden_size = 1024
else:
raise ValueError("Unsupported BERT model.")
 self.bert = BertModel.from_pretrained(bert_model ).to(device)
 self.head = Head(self.bert_hidden_size ).to(device)
 def forward(self, token_tensor, offsets):
token_tensor = token_tensor.to(self.device)
 bert_outputs, _ = self.bert(
 token_tensor, attention_mask=(token_tensor > 0 ).long() ,
token_type_ids=None, output_all_encoded_layers=False)
 head_outputs = self.head(bert_outputs, offsets.to(self.device))
return head_outputs
def children(m):
return m if isinstance(m,(list, tuple)) else list(m.children())
 def set_trainable_attr(m, b):
m.trainable = b
for p in m.parameters() :
p.requires_grad = b
def apply_leaf(m, f):
c = children(m)
 if isinstance(m, nn.Module):
f(m)
 if len(c)> 0:
for l in c:
apply_leaf(l, f)
 def set_trainable(l, b):
apply_leaf(l, lambda m: set_trainable_attr(m, b))
class GAPBot(BaseBot):
def __init__(self, model, train_loader, val_loader, *, optimizer, clip_grad=0,
avg_window=100, log_dir="./cache/logs/", log_level=logging.INFO,
checkpoint_dir="./cache/model_cache/", batch_idx=0, echo=False,
device="cuda:0", use_tensorboard=False):
super().__init__(
 model, train_loader, val_loader,
optimizer=optimizer, clip_grad=clip_grad,
log_dir=log_dir, checkpoint_dir=checkpoint_dir,
batch_idx=batch_idx, echo=echo,
device=device, use_tensorboard=use_tensorboard 
)
 self.criterion = torch.nn.CrossEntropyLoss()
self.loss_format = "%.6f"
def extract_prediction(self, tensor):
return tensor
def snapshot(self):

 loss = self.eval(self.val_loader)
 loss_str = self.loss_format % loss
self.logger.info("Snapshot loss %s", loss_str)
 self.logger.tb_scalars(
 "losses", {"val": loss}, self.step)
 target_path =(
 self.checkpoint_dir / "best.pth")
 if not self.best_performers or(self.best_performers[0][0] > loss):
torch.save(self.model.state_dict() , target_path)
 self.best_performers = [(loss, target_path, self.step)]
self.logger.info("Saving checkpoint %s...", target_path)
 else:
new_loss_str = self.loss_format % self.best_performers[0][0]
self.logger.info("This performance:%s is not as a good as our previously saved:%s", loss_str,new_loss_str)
 assert Path(target_path ).exists()
return loss
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])
 zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3])
 shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])
 return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))<categorify>
df_train = pd.read_csv("gap-test.tsv", delimiter="\t")
 df_val = pd.read_csv("gap-validation.tsv", delimiter="\t")
 df_test = pd.read_csv("/kaggle/input/gendered-pronoun-resolution/test_stage_2.tsv", delimiter="\t")
 sample_sub = pd.read_csv("/kaggle/input/gendered-pronoun-resolution/sample_submission_stage_2.csv")
 assert sample_sub.shape[0] == df_test.shape[0]
def transform(image,label):
DIM = IMAGE_SIZE[0]
XDIM = DIM%2
rot = 15.* tf.random.normal([1],dtype='float32')
 shr = 5.* tf.random.normal([1],dtype='float32')
 h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 h_shift = 16.* tf.random.normal([1],dtype='float32')
 w_shift = 16.* tf.random.normal([1],dtype='float32')
 m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
 x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM)
 y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM])
 z = tf.ones([DIM*DIM],dtype='int32')
 idx = tf.stack([x,y,z])
 idx2 = K.dot(m,tf.cast(idx,dtype='float32'))
idx2 = K.cast(idx2,dtype='int32')
 idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)
 idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
 d = tf.gather_nd(image,tf.transpose(idx3))
return tf.reshape(d,[DIM,DIM,3]),label<categorify>
tokenizer = BertTokenizer.from_pretrained(
 BERT_MODEL,
do_lower_case=CASED,
never_split =("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]", "[A]", "[B]", "[P]")
)
 tokenizer.vocab["[A]"] = -1
tokenizer.vocab["[B]"] = -1
tokenizer.vocab["[P]"] = -1
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 return image, label
def get_training_dataset(dataset,do_aug=True):
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 if do_aug: dataset = dataset.map(transform, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = 0 if SKIP_VALIDATION else count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<set_options>
train_ds = GAPDataset(df_train, tokenizer)
 val_ds = GAPDataset(df_val, tokenizer)
 test_ds = GAPDataset(df_test, tokenizer, labeled=False)
 train_loader = DataLoader(
 train_ds,
collate_fn = collate_examples,
batch_size=20,
num_workers=2,
pin_memory=True,
shuffle=True,
drop_last=True 
)
 val_loader = DataLoader(
 val_ds,
collate_fn = collate_examples,
batch_size=128,
num_workers=2,
pin_memory=True,
shuffle=False 
)
 test_loader = DataLoader(
 test_ds,
collate_fn = collate_examples,
batch_size=128,
num_workers=2,
pin_memory=True,
shuffle=False 
)
gc.collect()<define_variables>
model = GAPModel(BERT_MODEL, torch.device("cuda:0"))
set_trainable(model.bert, False)
 set_trainable(model.head, True )
models = []
histories = []<choose_model_class>
lr=1e-4
weight_decay=5e-3
optimizer = torch.optim.Adam(model.parameters() , lr=lr, weight_decay=weight_decay)
 bot = GAPBot(
 model, train_loader, val_loader,
optimizer=optimizer, echo=True,
avg_window=25
)
<set_options>
steps_per_epoch = len(train_loader)
 n_steps = steps_per_epoch * 27
bot.train(
 n_steps,
log_interval=steps_per_epoch // 4,
snapshot_interval=steps_per_epoch,
scheduler=TriangularLR(
 optimizer, 20, ratio=2, steps_per_cycle=n_steps)
 )
gc.collect()<choose_model_class>
bot.load_model(bot.best_performers[0][1] )
def get_model() :
with strategy.scope() :
enet = DenseNet201(
 input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights='imagenet',
include_top=False 
)
 enet.trainable = True
model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
def train_cross_validate(folds = 5):
histories = []
models = []
train_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[trn_ind]['TRAINING_FILENAMES']), labeled = True)
 val_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[val_ind]['TRAINING_FILENAMES']), labeled = True, ordered = True)
 model = get_model()
history = model.fit(
 get_training_dataset(train_dataset),
steps_per_epoch = STEPS_PER_EPOCH,
epochs = EPOCHS,
callbacks = [lr_callback],
validation_data = get_validation_dataset(val_dataset),
verbose=2 
)
 return history, model
def train_and_predict(folds = 5):
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 print('Start training %i folds'%folds)
 histories, models = train_cross_validate(folds = folds)
 print('Computing predictions...')
 probabilities = models.predict(test_images_ds)
 return probabilities
p1 = train_and_predict(folds=FOLDS )<set_options>
def predict(loader, *, return_y=False):
model.eval()
outputs, y_global = [], []
with torch.set_grad_enabled(False):
for input_tensors in loader:
input_tensors = [x.to(model.device)for x in input_tensors if x is not None]
outputs.append(bot.predict_batch(input_tensors ).cpu())
 outputs = torch.cat(outputs, dim=0)
 return outputs
gc.collect()<choose_model_class>
preds = predict(test_loader )
<define_variables>
from torch.autograd import Variable
<compute_test_metric>
def exx(row):
if(row.A > row.B and row.A > row.NEITHER):
row.A = 1
row.B = 0
row.NEITHER = 0
elif(row.B > row.A and row.B > row.NEITHER):
row.A = 0
row.B = 1
row.NEITHER = 0
else:
row.A = 0
row.B = 0
row.NEITHER = 1
return row
<save_to_csv><EOS> 
df_sub = pd.DataFrame(torch.softmax(preds, -1 ).cpu().numpy().clip(1e-3, 1-1e-3), columns=["A", "B", "NEITHER"])
 df_sub["ID"] = df_test.ID
df_sub.to_csv("submission.csv", index=False)
 df_sub.head()