repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
P-STMO | P-STMO-main/in_the_wild/videopose_PSTMO.py | import os
import time
from common.arguments import parse_args
from common.camera import *
from common.generators import *
from common.loss import *
from common.model import *
from common.utils import Timer, evaluate, add_path
from common.inference_3d import *
from model.block.refine import refine
from model.stmo import Model
# from joints_detectors.openpose.main import generate_kpts as open_pose
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
metadata = {'layout_name': 'coco', 'num_joints': 17, 'keypoints_symmetry': [[1, 3, 5, 7, 9, 11, 13, 15], [2, 4, 6, 8, 10, 12, 14, 16]]}
add_path()
# record time
def ckpt_time(ckpt=None):
if not ckpt:
return time.time()
else:
return time.time() - float(ckpt), time.time()
time0 = ckpt_time()
def get_detector_2d(detector_name):
def get_alpha_pose():
from joints_detectors.Alphapose.gene_npz import generate_kpts as alpha_pose
return alpha_pose
def get_hr_pose():
from joints_detectors.hrnet.pose_estimation.video import generate_kpts as hr_pose
return hr_pose
detector_map = {
'alpha_pose': get_alpha_pose,
'hr_pose': get_hr_pose,
# 'open_pose': open_pose
}
assert detector_name in detector_map, f'2D detector: {detector_name} not implemented yet!'
return detector_map[detector_name]()
class Skeleton:
def parents(self):
return np.array([-1, 0, 1, 2, 0, 4, 5, 0, 7, 8, 9, 8, 11, 12, 8, 14, 15])
def joints_right(self):
return [1, 2, 3, 14, 15, 16]
def main(args):
detector_2d = get_detector_2d(args.detector_2d)
assert detector_2d, 'detector_2d should be in ({alpha, hr, open}_pose)'
# 2D kpts loads or generate
#args.input_npz = './outputs/alpha_pose_skiing_cut/skiing_cut.npz'
if not args.input_npz:
video_name = args.viz_video
keypoints = detector_2d(video_name)
else:
npz = np.load(args.input_npz)
keypoints = npz['kpts'] # (N, 17, 2)
keypoints_symmetry = metadata['keypoints_symmetry']
kps_left, kps_right = list(keypoints_symmetry[0]), list(keypoints_symmetry[1])
joints_left, joints_right = list([4, 5, 6, 11, 12, 13]), list([1, 2, 3, 14, 15, 16])
# normlization keypoints Suppose using the camera parameter
keypoints = normalize_screen_coordinates(keypoints[..., :2], w=1000, h=1002)
# model_pos = TemporalModel(17, 2, 17, filter_widths=[3, 3, 3, 3, 3], causal=args.causal, dropout=args.dropout, channels=args.channels,
# dense=args.dense)
model = {}
model['trans'] = Model(args).cuda()
# if torch.cuda.is_available():
# model_pos = model_pos.cuda()
ckpt, time1 = ckpt_time(time0)
print('-------------- load data spends {:.2f} seconds'.format(ckpt))
# load trained model
# chk_filename = os.path.join(args.checkpoint, args.resume if args.resume else args.evaluate)
# print('Loading checkpoint', chk_filename)
# checkpoint = torch.load(chk_filename, map_location=lambda storage, loc: storage) # 把loc映射到storage
# model_pos.load_state_dict(checkpoint['model_pos'])
model_dict = model['trans'].state_dict()
no_refine_path = "checkpoint/PSTMOS_no_refine_48_5137_in_the_wild.pth"
pre_dict = torch.load(no_refine_path)
for key, value in pre_dict.items():
name = key[7:]
model_dict[name] = pre_dict[key]
model['trans'].load_state_dict(model_dict)
ckpt, time2 = ckpt_time(time1)
print('-------------- load 3D model spends {:.2f} seconds'.format(ckpt))
# Receptive field: 243 frames for args.arc [3, 3, 3, 3, 3]
receptive_field = args.frames
pad = (receptive_field - 1) // 2 # Padding on each side
causal_shift = 0
print('Rendering...')
input_keypoints = keypoints.copy()
print(input_keypoints.shape)
# gen = UnchunkedGenerator(None, None, [input_keypoints],
# pad=pad, causal_shift=causal_shift, augment=args.test_time_augmentation,
# kps_left=kps_left, kps_right=kps_right, joints_left=joints_left, joints_right=joints_right)
# test_data = Fusion(opt=args, train=False, dataset=dataset, root_path=root_path, MAE=opt.MAE)
# test_dataloader = torch.utils.data.DataLoader(test_data, batch_size=1,
# shuffle=False, num_workers=0, pin_memory=True)
#prediction = evaluate(gen, model_pos, return_predictions=True)
gen = Evaluate_Generator(128, None, None, [input_keypoints], args.stride,
pad=pad, causal_shift=causal_shift, augment=args.test_time_augmentation, shuffle=False,
kps_left=kps_left, kps_right=kps_right, joints_left=joints_left, joints_right=joints_right)
prediction = val(args, gen, model)
# save 3D joint points
np.save(f'outputs/test_3d_{args.video_name}_output.npy', prediction, allow_pickle=True)
rot = np.array([0.14070565, -0.15007018, -0.7552408, 0.62232804], dtype=np.float32)
prediction = camera_to_world(prediction, R=rot, t=0)
# We don't have the trajectory, but at least we can rebase the height
prediction[:, :, 2] -= np.min(prediction[:, :, 2])
np.save(f'outputs/test_3d_output_{args.video_name}_postprocess.npy', prediction, allow_pickle=True)
anim_output = {'Ours': prediction}
input_keypoints = image_coordinates(input_keypoints[..., :2], w=1000, h=1002)
ckpt, time3 = ckpt_time(time2)
print('-------------- generate reconstruction 3D data spends {:.2f} seconds'.format(ckpt))
if not args.viz_output:
args.viz_output = 'outputs/alpha_result.mp4'
from common.visualization import render_animation
render_animation(input_keypoints, anim_output,
Skeleton(), 25, args.viz_bitrate, np.array(70., dtype=np.float32), args.viz_output,
limit=args.viz_limit, downsample=args.viz_downsample, size=args.viz_size,
input_video_path=args.viz_video, viewport=(1000, 1002),
input_video_skip=args.viz_skip)
ckpt, time4 = ckpt_time(time3)
print('total spend {:2f} second'.format(ckpt))
def inference_video(video_path, detector_2d):
"""
Do image -> 2d points -> 3d points to video.
:param detector_2d: used 2d joints detector. Can be {alpha_pose, hr_pose}
:param video_path: relative to outputs
:return: None
"""
args = parse_args()
args.detector_2d = detector_2d
dir_name = os.path.dirname(video_path)
basename = os.path.basename(video_path)
args.video_name = basename[:basename.rfind('.')]
args.viz_video = video_path
# args.viz_export = f'{dir_name}/{args.detector_2d}_{video_name}_data.npy'
args.viz_output = f'{dir_name}/{args.detector_2d}_{args.video_name}.mp4'
# args.viz_limit = 20
#args.input_npz = 'outputs/alpha_pose_test/test.npz'
args.evaluate = 'pretrained_h36m_detectron_coco.bin'
with Timer(video_path):
main(args)
if __name__ == '__main__':
inference_video('outputs/skiing_cut.mp4', 'alpha_pose')
| 7,170 | 35.217172 | 139 | py |
P-STMO | P-STMO-main/in_the_wild/inference_3d.py | # Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import hashlib
import os
import pathlib
import shutil
import sys
import time
import cv2
import numpy as np
import torch
from torch.autograd import Variable
def get_varialbe(target):
num = len(target)
var = []
for i in range(num):
temp = Variable(target[i]).contiguous().cuda().type(torch.cuda.FloatTensor)
var.append(temp)
return var
def input_augmentation(input_2D, input_2D_flip, model_trans, joints_left, joints_right):
B, T, J, C = input_2D.shape
input_2D_flip = input_2D_flip.view(B, T, J, C, 1).permute(0, 3, 1, 2, 4)
input_2D_non_flip = input_2D.view(B, T, J, C, 1).permute(0, 3, 1, 2, 4)
output_3D_flip, output_3D_flip_VTE = model_trans(input_2D_flip)
output_3D_flip_VTE[:, 0] *= -1
output_3D_flip[:, 0] *= -1
output_3D_flip_VTE[:, :, :, joints_left + joints_right] = output_3D_flip_VTE[:, :, :, joints_right + joints_left]
output_3D_flip[:, :, :, joints_left + joints_right] = output_3D_flip[:, :, :, joints_right + joints_left]
output_3D_non_flip, output_3D_non_flip_VTE = model_trans(input_2D_non_flip)
output_3D_VTE = (output_3D_non_flip_VTE + output_3D_flip_VTE) / 2
output_3D = (output_3D_non_flip + output_3D_flip) / 2
input_2D = input_2D_non_flip
return input_2D, output_3D, output_3D_VTE
def step(opt, dataLoader, model, optimizer=None, epoch=None):
model_trans = model['trans']
model_trans.eval()
joints_left = [4, 5, 6, 11, 12, 13]
joints_right = [1, 2, 3, 14, 15, 16]
epoch_cnt=0
out = []
for _, batch, batch_2d, batch_2d_flip in dataLoader.next_epoch():
#[gt_3D, input_2D] = get_varialbe([batch, batch_2d])
#input_2D = Variable(batch_2d).contiguous().cuda().type(torch.cuda.FloatTensor)
input_2D = torch.from_numpy(batch_2d.astype('float32'))
input_2D_flip = torch.from_numpy(batch_2d_flip.astype('float32'))
if torch.cuda.is_available():
input_2D = input_2D.cuda()
input_2D_flip = input_2D_flip.cuda()
N = input_2D.size(0)
# out_target = gt_3D.clone().view(N, -1, opt.out_joints, opt.out_channels)
# out_target[:, :, 0] = 0
# gt_3D = gt_3D.view(N, -1, opt.out_joints, opt.out_channels).type(torch.cuda.FloatTensor)
#
# if out_target.size(1) > 1:
# out_target_single = out_target[:, opt.pad].unsqueeze(1)
# gt_3D_single = gt_3D[:, opt.pad].unsqueeze(1)
# else:
# out_target_single = out_target
# gt_3D_single = gt_3D
input_2D, output_3D, output_3D_VTE = input_augmentation(input_2D, input_2D_flip, model_trans, joints_left, joints_right)
output_3D_VTE = output_3D_VTE.permute(0, 2, 3, 4, 1).contiguous().view(N, -1, opt.out_joints, opt.out_channels)
output_3D = output_3D.permute(0, 2, 3, 4, 1).contiguous().view(N, -1, opt.out_joints, opt.out_channels)
output_3D_single = output_3D
pred_out = output_3D_single
input_2D = input_2D.permute(0, 2, 3, 1, 4).view(N, -1, opt.n_joints, 2)
pred_out[:, :, 0, :] = 0
if epoch_cnt == 0:
out = pred_out.squeeze(1).cpu()
else:
out = torch.cat((out, pred_out.squeeze(1).cpu()), dim=0)
epoch_cnt +=1
return out.numpy()
def val(opt, val_loader, model):
with torch.no_grad():
return step(opt, val_loader, model) | 3,586 | 32.523364 | 128 | py |
P-STMO | P-STMO-main/model/stmo.py | import torch
import torch.nn as nn
from model.block.vanilla_transformer_encoder import Transformer
from model.block.strided_transformer_encoder import Transformer as Transformer_reduce
class Linear(nn.Module):
def __init__(self, linear_size, p_dropout=0.25):
super(Linear, self).__init__()
self.l_size = linear_size
self.relu = nn.LeakyReLU(0.2, inplace=True)
self.dropout = nn.Dropout(p_dropout)
#self.w1 = nn.Linear(self.l_size, self.l_size)
self.w1 = nn.Conv1d(self.l_size, self.l_size, kernel_size=1)
self.batch_norm1 = nn.BatchNorm1d(self.l_size)
#self.w2 = nn.Linear(self.l_size, self.l_size)
self.w2 = nn.Conv1d(self.l_size, self.l_size, kernel_size=1)
self.batch_norm2 = nn.BatchNorm1d(self.l_size)
def forward(self, x):
y = self.w1(x)
y = self.batch_norm1(y)
y = self.relu(y)
y = self.dropout(y)
y = self.w2(y)
y = self.batch_norm2(y)
y = self.relu(y)
y = self.dropout(y)
out = x + y
return out
class FCBlock(nn.Module):
def __init__(self, channel_in, channel_out, linear_size, block_num):
super(FCBlock, self).__init__()
self.linear_size = linear_size
self.block_num = block_num
self.layers = []
self.channel_in = channel_in
self.stage_num = 3
self.p_dropout = 0.1
#self.fc_1 = nn.Linear(self.channel_in, self.linear_size)
self.fc_1 = nn.Conv1d(self.channel_in, self.linear_size, kernel_size=1)
self.bn_1 = nn.BatchNorm1d(self.linear_size)
for i in range(block_num):
self.layers.append(Linear(self.linear_size, self.p_dropout))
#self.fc_2 = nn.Linear(self.linear_size, channel_out)
self.fc_2 = nn.Conv1d(self.linear_size, channel_out, kernel_size=1)
self.layers = nn.ModuleList(self.layers)
self.relu = nn.LeakyReLU(0.2, inplace=True)
self.dropout = nn.Dropout(self.p_dropout)
def forward(self, x):
x = self.fc_1(x)
x = self.bn_1(x)
x = self.relu(x)
x = self.dropout(x)
for i in range(self.block_num):
x = self.layers[i](x)
x = self.fc_2(x)
return x
class Model(nn.Module):
def __init__(self, args):
super().__init__()
layers, channel, d_hid, length = args.layers, args.channel, args.d_hid, args.frames
stride_num = args.stride_num
self.num_joints_in, self.num_joints_out = args.n_joints, args.out_joints
self.encoder = FCBlock(2*self.num_joints_in, channel, 2*channel, 1)
self.Transformer = Transformer(layers, channel, d_hid, length=length)
self.Transformer_reduce = Transformer_reduce(len(stride_num), channel, d_hid, \
length=length, stride_num=stride_num)
self.fcn = nn.Sequential(
nn.BatchNorm1d(channel, momentum=0.1),
nn.Conv1d(channel, 3*self.num_joints_out, kernel_size=1)
)
self.fcn_1 = nn.Sequential(
nn.BatchNorm1d(channel, momentum=0.1),
nn.Conv1d(channel, 3*self.num_joints_out, kernel_size=1)
)
def forward(self, x):
x = x[:, :, :, :, 0].permute(0, 2, 3, 1).contiguous()
x_shape = x.shape
x = x.view(x.shape[0], x.shape[1], -1)
x = x.permute(0, 2, 1).contiguous()
x = self.encoder(x)
x = x.permute(0, 2, 1).contiguous()
x = self.Transformer(x)
x_VTE = x
x_VTE = x_VTE.permute(0, 2, 1).contiguous()
x_VTE = self.fcn_1(x_VTE)
x_VTE = x_VTE.view(x_shape[0], self.num_joints_out, -1, x_VTE.shape[2])
x_VTE = x_VTE.permute(0, 2, 3, 1).contiguous().unsqueeze(dim=-1)
x = self.Transformer_reduce(x)
x = x.permute(0, 2, 1).contiguous()
x = self.fcn(x)
x = x.view(x_shape[0], self.num_joints_out, -1, x.shape[2])
x = x.permute(0, 2, 3, 1).contiguous().unsqueeze(dim=-1)
return x, x_VTE
| 4,047 | 30.874016 | 92 | py |
P-STMO | P-STMO-main/model/stmo_pretrain.py | import torch
import torch.nn as nn
from model.block.vanilla_transformer_encoder_pretrain import Transformer, Transformer_dec
from model.block.strided_transformer_encoder import Transformer as Transformer_reduce
import numpy as np
class LayerNorm(nn.Module):
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
class Linear(nn.Module):
def __init__(self, linear_size, p_dropout=0.25):
super(Linear, self).__init__()
self.l_size = linear_size
self.relu = nn.LeakyReLU(0.2, inplace=True)
self.dropout = nn.Dropout(p_dropout)
#self.w1 = nn.Linear(self.l_size, self.l_size)
self.w1 = nn.Conv1d(self.l_size, self.l_size, kernel_size=1)
self.batch_norm1 = nn.BatchNorm1d(self.l_size)
#self.w2 = nn.Linear(self.l_size, self.l_size)
self.w2 = nn.Conv1d(self.l_size, self.l_size, kernel_size=1)
self.batch_norm2 = nn.BatchNorm1d(self.l_size)
def forward(self, x):
y = self.w1(x)
y = self.batch_norm1(y)
y = self.relu(y)
y = self.dropout(y)
y = self.w2(y)
y = self.batch_norm2(y)
y = self.relu(y)
y = self.dropout(y)
out = x + y
return out
class FCBlock(nn.Module):
def __init__(self, channel_in, channel_out, linear_size, block_num):
super(FCBlock, self).__init__()
self.linear_size = linear_size
self.block_num = block_num
self.layers = []
self.channel_in = channel_in
self.stage_num = 3
self.p_dropout = 0.1
#self.fc_1 = nn.Linear(self.channel_in, self.linear_size)
self.fc_1 = nn.Conv1d(self.channel_in, self.linear_size, kernel_size=1)
self.bn_1 = nn.BatchNorm1d(self.linear_size)
for i in range(block_num):
self.layers.append(Linear(self.linear_size, self.p_dropout))
#self.fc_2 = nn.Linear(self.linear_size, channel_out)
self.fc_2 = nn.Conv1d(self.linear_size, channel_out, kernel_size=1)
self.layers = nn.ModuleList(self.layers)
self.relu = nn.LeakyReLU(0.2, inplace=True)
self.dropout = nn.Dropout(self.p_dropout)
def forward(self, x):
x = self.fc_1(x)
x = self.bn_1(x)
x = self.relu(x)
x = self.dropout(x)
for i in range(self.block_num):
x = self.layers[i](x)
x = self.fc_2(x)
return x
class Model_MAE(nn.Module):
def __init__(self, args):
super().__init__()
layers, channel, d_hid, length = args.layers, args.channel, args.d_hid, args.frames
stride_num = args.stride_num
self.spatial_mask_num = args.spatial_mask_num
self.num_joints_in, self.num_joints_out = args.n_joints, args.out_joints
self.length = length
dec_dim_shrink = 2
self.encoder = FCBlock(2*self.num_joints_in, channel, 2*channel, 1)
self.Transformer = Transformer(layers, channel, d_hid, length=length)
self.Transformer_dec = Transformer_dec(layers-1, channel//dec_dim_shrink, d_hid//dec_dim_shrink, length=length)
self.encoder_to_decoder = nn.Linear(channel, channel//dec_dim_shrink, bias=False)
self.encoder_LN = LayerNorm(channel)
self.fcn_dec = nn.Sequential(
nn.BatchNorm1d(channel//dec_dim_shrink, momentum=0.1),
nn.Conv1d(channel//dec_dim_shrink, 2*self.num_joints_out, kernel_size=1)
)
# self.fcn_1 = nn.Sequential(
# nn.BatchNorm1d(channel, momentum=0.1),
# nn.Conv1d(channel, 3*self.num_joints_out, kernel_size=1)
# )
self.dec_pos_embedding = nn.Parameter(torch.randn(1, length, channel//dec_dim_shrink))
self.mask_token = nn.Parameter(torch.randn(1, 1, channel//dec_dim_shrink))
self.spatial_mask_token = nn.Parameter(torch.randn(1, 1, 2))
def forward(self, x_in, mask, spatial_mask):
x_in = x_in[:, :, :, :, 0].permute(0, 2, 3, 1).contiguous()
b,f,_,_ = x_in.shape
# spatial mask out
x = x_in.clone()
x[:,spatial_mask] = self.spatial_mask_token.expand(b,self.spatial_mask_num*f,2)
x = x.view(b, f, -1)
x = x.permute(0, 2, 1).contiguous()
x = self.encoder(x)
x = x.permute(0, 2, 1).contiguous()
feas = self.Transformer(x, mask_MAE=mask)
feas = self.encoder_LN(feas)
feas = self.encoder_to_decoder(feas)
B, N, C = feas.shape
# we don't unshuffle the correct visible token order,
# but shuffle the pos embedding accorddingly.
expand_pos_embed = self.dec_pos_embedding.expand(B, -1, -1).clone()
pos_emd_vis = expand_pos_embed[:, ~mask].reshape(B, -1, C)
pos_emd_mask = expand_pos_embed[:, mask].reshape(B, -1, C)
x_full = torch.cat([feas + pos_emd_vis, self.mask_token + pos_emd_mask], dim=1)
x_out = self.Transformer_dec(x_full, pos_emd_mask.shape[1])
x_out = x_out.permute(0, 2, 1).contiguous()
x_out = self.fcn_dec(x_out)
x_out = x_out.view(b, self.num_joints_out, 2, -1)
x_out = x_out.permute(0, 2, 3, 1).contiguous().unsqueeze(dim=-1)
return x_out
| 5,518 | 32.652439 | 119 | py |
P-STMO | P-STMO-main/model/block/refine.py | import torch
import torch.nn as nn
from torch.autograd import Variable
fc_out = 256
fc_unit = 1024
class refine(nn.Module):
def __init__(self, opt):
super().__init__()
out_seqlen = 1
fc_in = opt.out_channels*2*out_seqlen*opt.n_joints
fc_out = opt.in_channels * opt.n_joints
self.post_refine = nn.Sequential(
nn.Linear(fc_in, fc_unit),
nn.ReLU(),
nn.Dropout(0.5,inplace=True),
nn.Linear(fc_unit, fc_out),
nn.Sigmoid()
)
def forward(self, x, x_1):
N, T, V,_ = x.size()
x_in = torch.cat((x, x_1), -1)
x_in = x_in.view(N, -1)
score = self.post_refine(x_in).view(N,T,V,2)
score_cm = Variable(torch.ones(score.size()), requires_grad=False).cuda() - score
x_out = x.clone()
x_out[:, :, :, :2] = score * x[:, :, :, :2] + score_cm * x_1[:, :, :, :2]
return x_out
| 948 | 24.648649 | 89 | py |
P-STMO | P-STMO-main/model/block/vanilla_transformer_encoder_pretrain.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import math
import os
import copy
def clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
class Encoder(nn.Module):
def __init__(self, layer, N):
super(Encoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, mask):
for layer in self.layers:
x = layer(x, mask)
return x
class LayerNorm(nn.Module):
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
def attention(query, key, value, mask=None, dropout=None):
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
p_attn = F.softmax(scores, dim=-1)
if dropout is not None:
p_attn = dropout(p_attn)
return torch.matmul(p_attn, value), p_attn
class SublayerConnection(nn.Module):
def __init__(self, size, dropout):
super(SublayerConnection, self).__init__()
self.norm = LayerNorm(size)
self.dropout = nn.Dropout(dropout)
def forward(self, x, sublayer):
return x + self.dropout(sublayer(self.norm(x)))
class EncoderLayer(nn.Module):
def __init__(self, size, self_attn, feed_forward, dropout):
super(EncoderLayer, self).__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 2)
self.size = size
def forward(self, x, mask):
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
return self.sublayer[1](x, self.feed_forward)
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1):
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
def forward(self, query, key, value, mask=None):
if mask is not None:
mask = mask.unsqueeze(1)
nbatches = query.size(0)
query, key, value = \
[l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
for l, x in zip(self.linears, (query, key, value))]
x, self.attn = attention(query, key, value, mask=mask, dropout=self.dropout)
x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)
return self.linears[-1](x)
class PositionwiseFeedForward(nn.Module):
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.gelu = nn.ReLU()
self.dropout = nn.Dropout(dropout)
def forward(self, x):
return self.w_2(self.dropout(self.gelu(self.w_1(x))))
class Transformer(nn.Module):
def __init__(self, n_layers=3, d_model=256, d_ff=512, h=8, dropout=0.1, length=27):
super(Transformer, self).__init__()
self.pos_embedding = nn.Parameter(torch.randn(1, length, d_model))
self.model = self.make_model(N=n_layers, d_model=d_model, d_ff=d_ff, h=h, dropout=dropout)
def forward(self, x, mask_MAE=None, mask=None):
x += self.pos_embedding
#print(str(mask_MAE))
if mask_MAE is not None:
B, _, C = x.shape
x_vis = x[:,~mask_MAE].reshape(B, -1, C) # ~mask means visible
x = self.model(x_vis, mask)
else:
x = self.model(x, mask)
return x
def make_model(self, N=3, d_model=256, d_ff=512, h=8, dropout=0.1):
c = copy.deepcopy
attn = MultiHeadedAttention(h, d_model)
ff = PositionwiseFeedForward(d_model, d_ff, dropout)
model = Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N)
return model
class Transformer_dec(nn.Module):
def __init__(self, n_layers=3, d_model=256, d_ff=512, h=8, dropout=0.1, length=27):
super(Transformer_dec, self).__init__()
self.model = self.make_model(N=n_layers, d_model=d_model, d_ff=d_ff, h=h, dropout=dropout)
def forward(self, x, return_token_num, mask=None):
x = self.model(x, mask)
return x
def make_model(self, N=3, d_model=256, d_ff=512, h=8, dropout=0.1):
c = copy.deepcopy
attn = MultiHeadedAttention(h, d_model)
ff = PositionwiseFeedForward(d_model, d_ff, dropout)
model = Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N)
return model
| 5,115 | 31.176101 | 98 | py |
P-STMO | P-STMO-main/model/block/strided_transformer_encoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import math
import os
import copy
def clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
class Encoder(nn.Module):
def __init__(self, layer, N, length, d_model):
super(Encoder, self).__init__()
self.layers = layer
self.norm = LayerNorm(d_model)
self.pos_embedding_1 = nn.Parameter(torch.randn(1, length, d_model))
self.pos_embedding_2 = nn.Parameter(torch.randn(1, length, d_model))
self.pos_embedding_3 = nn.Parameter(torch.randn(1, length, d_model))
def forward(self, x, mask):
for i, layer in enumerate(self.layers):
if i == 0:
x += self.pos_embedding_1[:, :x.shape[1]]
elif i == 1:
x += self.pos_embedding_2[:, :x.shape[1]]
elif i == 2:
x += self.pos_embedding_3[:, :x.shape[1]]
x = layer(x, mask, i)
return x
class LayerNorm(nn.Module):
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
def attention(query, key, value, mask=None, dropout=None):
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
p_attn = F.softmax(scores, dim=-1)
if dropout is not None:
p_attn = dropout(p_attn)
return torch.matmul(p_attn, value), p_attn
class SublayerConnection(nn.Module):
def __init__(self, size, dropout, stride_num, i):
super(SublayerConnection, self).__init__()
self.norm = LayerNorm(size)
self.dropout = nn.Dropout(dropout)
self.pooling = nn.MaxPool1d(1, stride_num[i])
def forward(self, x, sublayer, i=-1, stride_num=-1):
if i != -1:
if stride_num[i] != 1:
res = self.pooling(x.permute(0, 2, 1))
res = res.permute(0, 2, 1)
return res + self.dropout(sublayer(self.norm(x)))
else:
return x + self.dropout(sublayer(self.norm(x)))
else:
return x + self.dropout(sublayer(self.norm(x)))
class EncoderLayer(nn.Module):
def __init__(self, size, self_attn, feed_forward, dropout, stride_num, i):
super(EncoderLayer, self).__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.stride_num = stride_num
self.sublayer = clones(SublayerConnection(size, dropout, stride_num, i), 2)
self.size = size
def forward(self, x, mask, i):
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
x = self.sublayer[1](x, self.feed_forward, i, self.stride_num)
return x
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1):
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
def forward(self, query, key, value, mask=None):
if mask is not None:
mask = mask.unsqueeze(1)
nbatches = query.size(0)
query, key, value = [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
for l, x in zip(self.linears, (query, key, value))]
x, self.attn = attention(query, key, value, mask=mask,
dropout=self.dropout)
x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)
return self.linears[-1](x)
class PositionwiseFeedForward(nn.Module):
def __init__(self, d_model, d_ff, dropout=0.1, number = -1, stride_num=-1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Conv1d(d_model, d_ff, kernel_size=1, stride=1)
self.w_2 = nn.Conv1d(d_ff, d_model, kernel_size=3, stride=stride_num[number], padding = 1)
self.gelu = nn.ReLU()
self.dropout = nn.Dropout(dropout)
def forward(self, x):
x = x.permute(0, 2, 1)
x = self.w_2(self.dropout(self.gelu(self.w_1(x))))
x = x.permute(0, 2, 1)
return x
class Transformer(nn.Module):
def __init__(self, n_layers=3, d_model=256, d_ff=512, h=8, length=27, stride_num=None, dropout=0.1):
super(Transformer, self).__init__()
self.length = length
self.stride_num = stride_num
self.model = self.make_model(N=n_layers, d_model=d_model, d_ff=d_ff, h=h, dropout=dropout, length = self.length)
def forward(self, x, mask=None):
x = self.model(x, mask)
return x
def make_model(self, N=3, d_model=256, d_ff=512, h=8, dropout=0.1, length=27):
c = copy.deepcopy
attn = MultiHeadedAttention(h, d_model)
model_EncoderLayer = []
for i in range(N):
ff = PositionwiseFeedForward(d_model, d_ff, dropout, i, self.stride_num)
model_EncoderLayer.append(EncoderLayer(d_model, c(attn), c(ff), dropout, self.stride_num, i))
model_EncoderLayer = nn.ModuleList(model_EncoderLayer)
model = Encoder(model_EncoderLayer, N, length, d_model)
return model
| 5,685 | 32.05814 | 120 | py |
P-STMO | P-STMO-main/model/block/vanilla_transformer_encoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import math
import os
import copy
def clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
class Encoder(nn.Module):
def __init__(self, layer, N):
super(Encoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, mask):
for layer in self.layers:
x = layer(x, mask)
return x
class LayerNorm(nn.Module):
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
def attention(query, key, value, mask=None, dropout=None):
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
p_attn = F.softmax(scores, dim=-1)
if dropout is not None:
p_attn = dropout(p_attn)
return torch.matmul(p_attn, value), p_attn
class SublayerConnection(nn.Module):
def __init__(self, size, dropout):
super(SublayerConnection, self).__init__()
self.norm = LayerNorm(size)
self.dropout = nn.Dropout(dropout)
def forward(self, x, sublayer):
return x + self.dropout(sublayer(self.norm(x)))
class EncoderLayer(nn.Module):
def __init__(self, size, self_attn, feed_forward, dropout):
super(EncoderLayer, self).__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 2)
self.size = size
def forward(self, x, mask):
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
return self.sublayer[1](x, self.feed_forward)
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1):
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
def forward(self, query, key, value, mask=None):
if mask is not None:
mask = mask.unsqueeze(1)
nbatches = query.size(0)
query, key, value = \
[l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
for l, x in zip(self.linears, (query, key, value))]
x, self.attn = attention(query, key, value, mask=mask, dropout=self.dropout)
x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)
return self.linears[-1](x)
class PositionwiseFeedForward(nn.Module):
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.gelu = nn.ReLU()
self.dropout = nn.Dropout(dropout)
def forward(self, x):
return self.w_2(self.dropout(self.gelu(self.w_1(x))))
class Transformer(nn.Module):
def __init__(self, n_layers=3, d_model=256, d_ff=512, h=8, dropout=0.1, length=27):
super(Transformer, self).__init__()
self.pos_embedding = nn.Parameter(torch.randn(1, length, d_model))
self.model = self.make_model(N=n_layers, d_model=d_model, d_ff=d_ff, h=h, dropout=dropout)
def forward(self, x, mask=None):
x += self.pos_embedding
x = self.model(x, mask)
return x
def make_model(self, N=3, d_model=256, d_ff=512, h=8, dropout=0.1):
c = copy.deepcopy
attn = MultiHeadedAttention(h, d_model)
ff = PositionwiseFeedForward(d_model, d_ff, dropout)
model = Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N)
return model
| 4,191 | 30.283582 | 98 | py |
Namaste | Namaste-master/__init__.py | from namaste.namaste import *
| 30 | 14.5 | 29 | py |
Namaste | Namaste-master/namaste/Crossfield_transit.py | """
-------------------------------------------------------
The Mandel & Agol (2002) transit light curve equations.
-------------------------------------------------------
:FUNCTIONS:
:func:`occultuniform` -- uniform-disk transit light curve
:func:`occultquad` -- quadratic limb-darkening
:func:`occultnonlin` -- full (4-parameter) nonlinear limb-darkening
:func:`occultnonlin_small` -- small-planet approximation with full
nonlinear limb-darkening.
p
:func:`t2z` -- convert dates to transiting z-parameter for circular
orbits.
:REQUIREMENTS:
`numpy <http://www.numpy.org/>`_
`scipy.special <http://www.scipy.org/>`_
:NOTES:
Certain values of p (<0.09, >0.5) cause some routines to hang;
your mileage may vary. If you find out why, please let me know!
Cursory testing suggests that the Python routines contained within
are slower than the corresponding IDL code by a factor of 5-10.
For :func:`occultquad` I relied heavily on the IDL code of E. Agol
and J. Eastman.
Function :func:`appellf1` comes from the mpmath compilation, and
is adopted (with modification) for use herein in compliance with
its BSD license (see function documentation for more details).
:REFERENCE:
The main reference is that seminal work by `Mandel and Agol (2002)
<http://adsabs.harvard.edu/abs/2002ApJ...580L.171M>`_.
:LICENSE:
Created by `Ian Crossfield <http://www.astro.ucla.edu/~ianc/>`_ at
UCLA. The code contained herein may be reused, adapted, or
modified so long as proper attribution is made to the original
authors.
:REVISIONS:
2011-04-22 11:08 IJMC: Finished, renamed occultation functions.
Cleaned up documentation. Published to
website.
2011-04-25 17:32 IJMC: Fixed bug in :func:`ellpic_bulirsch`.
2012-03-09 08:38 IJMC: Several major bugs fixed, courtesy of
S. Aigrain at Oxford U.
2012-03-20 14:12 IJMC: Fixed modeleclipse_simple based on new
format of :func:`occultuniform. `
"""
import numpy as np
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
from scipy import special, misc
#import pdb
eps = np.finfo(float).eps
zeroval = eps*1e6
def appelf1_ac(a, b1, b2, c, z1, z2, **kwargs):
"""Analytic continuations of the Appell hypergeometric function of 2 variables.
:REFERENCE:
Olsson 1964, Colavecchia et al. 2001
"""
# 2012-03-09 12:05 IJMC: Created
def appellf1(a,b1,b2,c,z1,z2,**kwargs):
"""Give the Appell hypergeometric function of two variables.
:INPUTS:
six parameters, all scalars.
:OPTIONS:
eps -- scalar, machine tolerance precision. Defaults to 1e-10.
:NOTES:
Adapted from the `mpmath <http://code.google.com/p/mpmath/>`_
module, but using the scipy (instead of mpmath) Gauss
hypergeometric function speeds things up.
:LICENSE:
MPMATH Copyright (c) 2005-2010 Fredrik Johansson and mpmath
contributors. All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:
a. Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
b. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
c. Neither the name of mpmath nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
"""
#2011-04-22 10:15 IJMC: Adapted from mpmath, but using scipy Gauss
# hypergeo. function
# 2013-03-11 13:34 IJMC: Added a small error-trap for 'nan' hypgf values
if kwargs.has_key('eps'):
eps = kwargs['eps']
else:
eps = 1e-9
# Assume z1 smaller
# We will use z1 for the outer loop
if abs(z1) > abs(z2):
z1, z2 = z2, z1
b1, b2 = b2, b1
def ok(x):
return abs(x) < 0.99
# IJMC: Ignore the finite cases for now....
## Finite cases
#if ctx.isnpint(a):
# pass
#elif ctx.isnpint(b1):
# pass
#elif ctx.isnpint(b2):
# z1, z2, b1, b2 = z2, z1, b2, b1
#else:
# #z1, z2
# # Note: ok if |z2| > 1, because
# # 2F1 implements analytic continuation
if not ok(z1):
u1 = (z1-z2)/(z1-1)
if not ok(u1):
raise ValueError("Analytic continuation not implemented")
#print "Using analytic continuation"
return (1-z1)**(-b1)*(1-z2)**(c-a-b2)*\
appellf1(c-a,b1,c-b1-b2,c,u1,z2,**kwargs)
#print "inner is", a, b2, c
##one = ctx.one
s = 0
t = 1
k = 0
while 1:
#h = ctx.hyp2f1(a,b2,c,z2,zeroprec=ctx.prec,**kwargs)
#print a.__class__, b2.__class__, c.__class__, z2.__class__
h = special.hyp2f1(float(a), float(b2), float(c), float(z2))
if not np.isfinite(h):
break
term = t * h
if abs(term) < eps and abs(h) > 10*eps:
break
s += term
k += 1
t = (t*a*b1*z1) / (c*k)
c += 1 # one
a += 1 # one
b1 += 1 # one
#print k, h, term, s
#if (k/200.)==int(k/200.) or k==171: pdb.set_trace()
return s
def ellke2(k, tol=100*eps, maxiter=100):
"""Compute complete elliptic integrals of the first kind (K) and
second kind (E) using the series expansions."""
# 2011-04-24 21:14 IJMC: Created
k = np.array(k, copy=False)
ksum = 0*k
kprevsum = ksum.copy()
kresidual = ksum + 1
#esum = 0*k
#eprevsum = esum.copy()
#eresidual = esum + 1
n = 0
sqrtpi = np.sqrt(np.pi)
#kpow = k**0
#ksq = k*k
while (np.abs(kresidual) > tol).any() and n <= maxiter:
#kpow *= (ksq)
#print kpow==(k**(2*n))
ksum += ((misc.factorial2(2*n - 1)/misc.factorial2(2*n))**2) * k**(2*n)
#ksum += (special.gamma(n + 0.5)/special.gamma(n + 1) / sqrtpi) * k**(2*n)
kresidual = ksum - kprevsum
kprevsum = ksum.copy()
n += 1
#print n, kresidual
return ksum * (np.pi/2.)
def ellke(k):
"""Compute Hasting's polynomial approximation for the complete
elliptic integral of the first (ek) and second (kk) kind.
:INPUTS:
k -- scalar or Numpy array
:OUTPUTS:
ek, kk
:NOTES:
Adapted from the IDL function of the same name by J. Eastman (OSU).
"""
# 2011-04-19 09:15 IJC: Adapted from J. Eastman's IDL code.
m1 = 1. - k**2
logm1 = np.log(m1)
# First kind:
a1 = 0.44325141463
a2 = 0.06260601220
a3 = 0.04757383546
a4 = 0.01736506451
b1 = 0.24998368310
b2 = 0.09200180037
b3 = 0.04069697526
b4 = 0.00526449639
ee1 = 1. + m1*(a1 + m1*(a2 + m1*(a3 + m1*a4)))
ee2 = m1 * (b1 + m1*(b2 + m1*(b3 + m1*b4))) * (-logm1)
# Second kind:
a0 = 1.38629436112
a1 = 0.09666344259
a2 = 0.03590092383
a3 = 0.03742563713
a4 = 0.01451196212
b0 = 0.5
b1 = 0.12498593597
b2 = 0.06880248576
b3 = 0.03328355346
b4 = 0.00441787012
ek1 = a0 + m1*(a1 + m1*(a2 + m1*(a3 + m1*a4)))
ek2 = (b0 + m1*(b1 + m1*(b2 + m1*(b3 + m1*b4)))) * logm1
return ee1 + ee2, ek1 - ek2
def ellpic_bulirsch(n, k, tol=1000*eps, maxiter=1e4):
"""Compute the complete elliptical integral of the third kind
using the algorithm of Bulirsch (1965).
:INPUTS:
n -- scalar or Numpy array
k-- scalar or Numpy array
:NOTES:
Adapted from the IDL function of the same name by J. Eastman (OSU).
"""
# 2011-04-19 09:15 IJMC: Adapted from J. Eastman's IDL code.
# 2011-04-25 11:40 IJMC: Set a more stringent tolerance (from 1e-8
# to 1e-14), and fixed tolerance flag to the
# maximum of all residuals.
# 2013-04-13 21:31 IJMC: Changed 'max' call to 'any'; minor speed boost.
# Make p, k into vectors:
#if not hasattr(n, '__iter__'):
# n = array([n])
#if not hasattr(k, '__iter__'):
# k = array([k])
if not hasattr(n,'__iter__'):
n = np.array([n])
if not hasattr(k,'__iter__'):
k = np.array([k])
if len(n)==0 or len(k)==0:
return np.array([])
kc = np.sqrt(1. - k**2)
p = n + 1.
if min(p) < 0:
print("Negative p")
# Initialize:
m0 = np.array(1.)
c = np.array(1.)
p = np.sqrt(p)
d = 1./p
e = kc.copy()
outsideTolerance = True
iter = 0
while outsideTolerance and iter<maxiter:
f = c.copy()
c = d/p + c
g = e/p
d = 2. * (f*g + d)
p = g + p;
g = m0.copy()
m0 = kc + m0
if ((np.abs(1. - kc/g)) > tol).any():
kc = 2. * np.sqrt(e)
e = kc * m0
iter += 1
else:
outsideTolerance = False
#if (iter/10.) == (iter/10):
# print iter, (np.abs(1. - kc/g))
#pdb.set_trace()
## For debugging:
#print min(np.abs(1. - kc/g)) > tol
#print 'tolerance>>', tol
#print 'minimum>> ', min(np.abs(1. - kc/g))
#print 'maximum>> ', max(np.abs(1. - kc/g)) #, (np.abs(1. - kc/g))
return .5 * np.pi * (c*m0 + d) / (m0 * (m0 + p))
def z2dt_circular(per, inc, ars, z):
""" Convert transit crossing parameter z to a time offset for circular orbits.
:INPUTS:
per -- scalar. planetary orbital period
inc -- scalar. orbital inclination (in degrees)
ars -- scalar. ratio a/Rs, orbital semimajor axis over stellar radius
z -- scalar or array; transit crossing parameter z.
:RETURNS:
|dt| -- magnitude of the time offset from transit center at
which specified z occurs.
"""
# 2011-06-14 11:26 IJMC: Created.
numer = (z / ars)**2 - 1.
denom = np.cos(inc*np.pi/180.)**2 - 1.
dt = (per / (2*np.pi)) * np.arccos(np.sqrt(numer / denom))
return dt
def t2z(tt, per, inc, hjd, ars, ecc=0, longperi=0):
"""Convert HJD (time) to transit crossing parameter z.
:INPUTS:
tt -- scalar. transit ephemeris
per -- scalar. planetary orbital period
inc -- scalar. orbital inclination (in degrees)
hjd -- scalar or array of times, typically heliocentric or
barycentric julian date.
ars -- scalar. ratio a/Rs, orbital semimajor axis over stellar radius
ecc -- scalar. orbital eccentricity.
longperi=0 scalar. longitude of periapse (in radians)
:ALGORITHM:
At zero eccentricity, z relates to physical quantities by:
z = (a/Rs) * sqrt(sin[w*(t-t0)]**2+[cos(i)*cos(w*[t-t0])]**2)
"""
# 2010-01-11 18:18 IJC: Created
# 2011-04-19 15:20 IJMC: Updated documentation.
# 2011-04-22 11:27 IJMC: Updated to avoid reliance on planet objects.
# 2011-05-22 16:51 IJMC: Temporarily removed eccentricity
# dependence... I'll deal with that later.
#if not p.transit:
# print "Must use a transiting exoplanet!"
# return False
import Analysis as an
if ecc != 0:
ecc = 0
print("WARNING: setting ecc=0 for now until I get this function working")
if ecc==0:
omega_orb = 2*np.pi/per
omega_tdiff = omega_orb * (hjd - tt)
z = ars * np.sqrt(np.sin(omega_tdiff)**2 + \
(np.cos(inc*np.pi/180.)*np.cos(omega_tdiff))**2)
else:
if longperi is None:
longperi = 180.
f = an.trueanomaly(ecc, (2*np.pi/per) * (hjd - tt))
z = ars * (1. - ecc**2) * np.sqrt(1. - (np.sin(longperi + f) * np.sin(inc*np.pi/180.))**2) / \
(1. + ecc * np.cos(f))
return z
def uniform(*arg, **kw):
"""Placeholder for my old code; the new function is called
:func:`occultuniform`.
"""
# 2011-04-19 15:06 IJMC: Created
print("The function 'transit.uniform()' is deprecated.")
print("Please use transit.occultuniform() in the future.")
return occultuniform(*arg, **kw)
def occultuniform(z, p, complement=False, verbose=False):
"""Uniform-disk transit light curve (i.e., no limb darkening).
:INPUTS:
z -- scalar or sequence; positional offset values of planet in
units of the stellar radius.
p -- scalar; planet/star radius ratio.
complement : bool
If True, return (1 - occultuniform(z, p))
:SEE ALSO: :func:`t2z`, :func:`occultquad`, :func:`occultnonlin_small`
"""
# 2011-04-15 16:56 IJC: Added a tad of documentation
# 2011-04-19 15:21 IJMC: Cleaned up documentation.
# 2011-04-25 11:07 IJMC: Can now handle scalar z input.
# 2011-05-15 10:20 IJMC: Fixed indexing check (size, not len)
# 2012-03-09 08:30 IJMC: Added "complement" argument for backwards
# compatibility, and fixed arccos error at
# 1st/4th contact point (credit to
# S. Aigrain @ Oxford)
# 2013-04-13 21:28 IJMC: Some code optimization; ~20% gain.
z = np.abs(np.array(z,copy=True))
fsecondary = np.zeros(z.shape,float)
if p < 0:
pneg = True
p = np.abs(p)
else:
pneg = False
p2 = p*p
if len(z.shape)>0: # array entered
i1 = (1+p)<z
i2 = (np.abs(1-p) < z) * (z<= (1+p))
i3 = z<= (1-p)
i4 = z<=(p-1)
any2 = i2.any()
any3 = i3.any()
any4 = i4.any()
#print i1.sum(),i2.sum(),i3.sum(),i4.sum()
if any2:
zi2 = z[i2]
zi2sq = zi2*zi2
arg1 = 1 - p2 + zi2sq
acosarg1 = (p2+zi2sq-1)/(2.*p*zi2)
acosarg2 = arg1/(2*zi2)
acosarg1[acosarg1 > 1] = 1. # quick fix for numerical precision errors
acosarg2[acosarg2 > 1] = 1. # quick fix for numerical precision errors
k0 = np.arccos(acosarg1)
k1 = np.arccos(acosarg2)
k2 = 0.5*np.sqrt(4*zi2sq-arg1*arg1)
fsecondary[i2] = (1./np.pi)*(p2*k0 + k1 - k2)
fsecondary[i1] = 0.
if any3: fsecondary[i3] = p2
if any4: fsecondary[i4] = 1.
if verbose:
if not (i1+i2+i3+i4).all():
print("warning -- some input values not indexed!")
if (i1.sum()+i2.sum()+i3.sum()+i4.sum() != z.size):
print("warning -- indexing didn't get the right number of values")
else: # scalar entered
if (1+p)<=z:
fsecondary = 0.
elif (np.abs(1-p) < z) * (z<= (1+p)):
z2 = z*z
k0 = np.arccos((p2+z2-1)/(2.*p*z))
k1 = np.arccos((1-p2+z2)/(2*z))
k2 = 0.5*np.sqrt(4*z2-(1+z2-p2)**2)
fsecondary = (1./np.pi)*(p2*k0 + k1 - k2)
elif z<= (1-p):
fsecondary = p2
elif z<=(p-1):
fsecondary = 1.
if pneg:
fsecondary *= -1
if complement:
return fsecondary
else:
return 1. - fsecondary
def depthchisq(z, planet, data, ddepth=[-.1,.1], ndepth=20, w=None):
#z = transit.t2z(planet, planet.i, hjd, 0.211)
nobs = z.size
depths = np.linspace(ddepth[0],ddepth[1], ndepth)
print(depths)
chisq = np.zeros(ndepth, float)
for ii in range(ndepth):
tr = -(transit.occultuniform(z, np.sqrt(planet.depth))/depths[ii])
if w is None:
w = np.ones(nobs,float)/data[tr==0].std()
print('w>>',w[0])
baseline = np.ones(nobs,float) * an.wmean(data[tr==0], w[tr==0])
print('b>>',baseline[0])
print('d[ii]>>',depths[ii])
model = baseline + tr*depths[ii]
plot(model)
chisq[ii] = (w*(model-data)**2).sum()
return depths, chisq
def integral_smallplanet_nonlinear(z, p, cn, lower, upper):
"""Return the integral in I*(z) in Eqn. 8 of Mandel & Agol (2002).
-- Int[I(r) 2r dr]_{z-p}^{1}, where:
:INPUTS:
z = scalar or array. Distance between center of star &
planet, normalized by the stellar radius.
p = scalar. Planet/star radius ratio.
cn = 4-sequence. Nonlinear limb-darkening coefficients,
e.g. from Claret 2000.
lower, upper -- floats. Limits of integration in units of mu
:RETURNS:
value of the integral at specified z.
"""
# 2010-11-06 14:12 IJC: Created
# 2012-03-09 08:54 IJMC: Added a cheat for z very close to zero
#import pdb
z = np.array(z, copy=True)
z[z==0] = zeroval
lower = np.array(lower, copy=True)
upper = np.array(upper, copy=True)
a = (z - p)**2
return eval_int_at_limit(upper, cn) - eval_int_at_limit(lower, cn)
def eval_int_at_limit(limit, cn):
"""Evaluate the integral at a specified limit (upper or lower)"""
# 2013-04-17 22:27 IJMC: Implemented some speed boosts; added a
# bug; fixed it again.
# The old way:
#term1 = cn[0] * (1. - 0.8 * np.sqrt(limit))
#term2 = cn[1] * (1. - (2./3.) * limit)
#term3 = cn[2] * (1. - (4./7.) * limit**1.5)
#term4 = cn[3] * (1. - 0.5 * limit**2)
#goodret = -(limit**2) * (1. - term1 - term2 - term3 - term4)
# The new, somewhat faster, way:
sqrtlimit = np.sqrt(limit)
sqlimit = limit*limit
total = 1. - cn[0] * (1. - 0.8 * sqrtlimit)
total -= cn[1] * (1. - (2./3.) * limit)
total -= cn[2] * (1. - (4./7.) * limit*sqrtlimit)
total -= cn[3] * (1. - 0.5 * sqlimit)
return -(sqlimit) * total
def smallplanet_nonlinear(*arg, **kw):
"""Placeholder for backwards compatibility with my old code. The
function is now called :func:`occultnonlin_small`.
"""
# 2011-04-19 15:10 IJMC: Created
print("The function 'transit.smallplanet_nonlinear()' is deprecated.")
print("Please use transit.occultnonlin_small() in the future.")
return occultnonlin_small(*arg, **kw)
def occultnonlin_small(z,p, cn):
"""Nonlinear limb-darkening light curve in the small-planet
approximation (section 5 of Mandel & Agol 2002).
:INPUTS:
z -- sequence of positional offset values
p -- planet/star radius ratio
cn -- four-sequence nonlinear limb darkening coefficients. If
a shorter sequence is entered, the later values will be
set to zero.
:NOTE:
I had to divide the effect at the near-edge of the light curve
by pi for consistency; this factor was not in Mandel & Agol, so
I may have coded something incorrectly (or there was a typo).
:EXAMPLE:
::
# Reproduce Figure 2 of Mandel & Agol (2002):
from pylab import *
import transit
z = linspace(0, 1.2, 100)
cns = vstack((zeros(4), eye(4)))
figure()
for coef in cns:
f = transit.occultnonlin_small(z, 0.1, coef)
plot(z, f, '--')
:SEE ALSO:
:func:`t2z`
"""
# 2010-11-06 14:23 IJC: Created
# 2011-04-19 15:22 IJMC: Updated documentation. Renamed.
# 2011-05-24 14:00 IJMC: Now check the size of cn.
# 2012-03-09 08:54 IJMC: Added a cheat for z very close to zero
# 2013-04-17 10:51 IJMC: Mild code optimization
#import pdb
cn = np.array([cn], copy=True).ravel()
if cn.size < 4:
cn = np.concatenate((cn, [0.]*(4-cn.size)))
z = np.array(z, copy=False)
F = np.ones(z.shape, float)
z[z==0] = zeroval # cheat!
a = (z - p)**2
b = (z + p)**2
c0 = 1. - np.sum(cn)
Omega = 0.25 * c0 + np.sum( cn / np.arange(5., 9.) )
ind1 = ((1. - p) < z) * ((1. + p) > z)
ind2 = z <= (1. - p)
# Need to specify limits of integration in terms of mu (not r)
aind1 = 1. - a[ind1]
zind1 = z[ind1]
zind1m1 = zind1 - 1.
Istar_edge = integral_smallplanet_nonlinear(zind1, p, cn, \
np.sqrt(aind1), 0.) / aind1
zind2 = z[ind2]
Istar_inside = integral_smallplanet_nonlinear(zind2, p, cn, \
np.sqrt(1. - a[ind2]), \
np.sqrt(1. - b[ind2])) / \
(4. * zind2 * p)
term1 = 0.25 * Istar_edge / (np.pi * Omega)
term2 = p*p * np.arccos((zind1m1) / p)
term3 = (zind1m1) * np.sqrt(p*p - (zind1m1*zind1m1))
F[ind1] = 1. - term1 * (term2 - term3)
F[ind2] = 1. - 0.25 * p*p * Istar_inside / Omega
#pdb.set_trace()
return F
def occultquad(z,p0, gamma, retall=False, verbose=False):
"""Quadratic limb-darkening light curve; cf. Section 4 of Mandel & Agol (2002).
:INPUTS:
z -- sequence of positional offset values
p0 -- planet/star radius ratio
gamma -- two-sequence.
quadratic limb darkening coefficients. (c1=c3=0; c2 =
gamma[0] + 2*gamma[1], c4 = -gamma[1]). If only a single
gamma is used, then you're assuming linear limb-darkening.
:OPTIONS:
retall -- bool.
If True, in addition to the light curve return the
uniform-disk light curve, lambda^d, and eta^d parameters.
Using these quantities allows for quicker model generation
with new limb-darkening coefficients -- the speed boost is
roughly a factor of 50. See the second example below.
:EXAMPLE:
::
# Reproduce Figure 2 of Mandel & Agol (2002):
from pylab import *
import transit
z = linspace(0, 1.2, 100)
gammavals = [[0., 0.], [1., 0.], [2., -1.]]
figure()
for gammas in gammavals:
f = transit.occultquad(z, 0.1, gammas)
plot(z, f)
::
# Calculate the same geometric transit with two different
# sets of limb darkening coefficients:
from pylab import *
import transit
p, b = 0.1, 0.5
x = (arange(300.)/299. - 0.5)*2.
z = sqrt(x**2 + b**2)
gammas = [.25, .75]
F1, Funi, lambdad, etad = transit.occultquad(z, p, gammas, retall=True)
gammas = [.35, .55]
F2 = 1. - ((1. - gammas[0] - 2.*gammas[1])*(1. - F1) +
(gammas[0] + 2.*gammas[1])*(lambdad + 2./3.*(p > z)) + gammas[1]*etad) /
(1. - gammas[0]/3. - gammas[1]/6.)
figure()
plot(x, F1, x, F2)
legend(['F1', 'F2'])
:SEE ALSO:
:func:`t2z`, :func:`occultnonlin_small`, :func:`occultuniform`
:NOTES:
In writing this I relied heavily on the occultquad IDL routine
by E. Agol and J. Eastman, especially for efficient computation
of elliptical integrals and for identification of several
apparent typographic errors in the 2002 paper (see comments in
the source code).
From some cursory testing, this routine appears about 9 times
slower than the IDL version. The difference drops only
slightly when using precomputed quantities (i.e., retall=True).
A large portion of time is taken up in :func:`ellpic_bulirsch`
and :func:`ellke`, but at least as much is taken up by this
function itself. More optimization (or a C wrapper) is desired!
"""
# 2011-04-15 15:58 IJC: Created; forking from smallplanet_nonlinear
# 2011-05-14 22:03 IJMC: Now linear-limb-darkening is allowed with
# a single parameter passed in.
# 2013-04-13 21:06 IJMC: Various code tweaks; speed increased by
# ~20% in some cases.
#import pdb
# Initialize:
z = np.array(z, copy=False)
lambdad = np.zeros(z.shape, float)
etad = np.zeros(z.shape, float)
F = np.ones(z.shape, float)
p = np.abs(p0) # Save the original input
# Define limb-darkening coefficients:
if len(gamma) < 2 or not hasattr(gamma, '__iter__'): # Linear limb-darkening
gamma = np.concatenate([np.ravel(gamma), [0.]])
c2 = gamma[0]
else:
c2 = gamma[0] + 2 * gamma[1]
c4 = -gamma[1]
# Test the simplest case (a zero-sized planet):
if p==0:
if retall:
ret = np.ones(z.shape, float), np.ones(z.shape, float), \
np.zeros(z.shape, float), np.zeros(z.shape, float)
else:
ret = np.ones(z.shape, float)
return ret
# Define useful constants:
fourOmega = 1. - gamma[0]/3. - gamma[1]/6. # Actually 4*Omega
a = (z - p)*(z - p)
b = (z + p)*(z + p)
k = 0.5 * np.sqrt((1. - a) / (z * p))
p2 = p*p
z2 = z*z
ninePi = 9*np.pi
# Define the many necessary indices for the different cases:
pgt0 = p > 0
i01 = pgt0 * (z >= (1. + p))
i02 = pgt0 * (z > (.5 + np.abs(p - 0.5))) * (z < (1. + p))
i03 = pgt0 * (p < 0.5) * (z > p) * (z < (1. - p))
i04 = pgt0 * (p < 0.5) * (z == (1. - p))
i05 = pgt0 * (p < 0.5) * (z == p)
i06 = (p == 0.5) * (z == 0.5)
i07 = (p > 0.5) * (z == p)
i08 = (p > 0.5) * (z >= np.abs(1. - p)) * (z < p)
i09 = pgt0 * (p < 1) * (z > 0) * (z < (0.5 - np.abs(p - 0.5)))
i10 = pgt0 * (p < 1) * (z == 0)
i11 = (p > 1) * (z >= 0.) * (z < (p - 1.))
#any01 = i01.any()
#any02 = i02.any()
#any03 = i03.any()
any04 = i04.any()
any05 = i05.any()
any06 = i06.any()
any07 = i07.any()
#any08 = i08.any()
#any09 = i09.any()
any10 = i10.any()
any11 = i11.any()
#print n01, n02, n03, n04, n05, n06, n07, n08, n09, n10, n11
if verbose:
allind = i01 + i02 + i03 + i04 + i05 + i06 + i07 + i08 + i09 + i10 + i11
nused = (i01.sum() + i02.sum() + i03.sum() + i04.sum() + \
i05.sum() + i06.sum() + i07.sum() + i08.sum() + \
i09.sum() + i10.sum() + i11.sum())
print("%i/%i indices used" % (nused, i01.size))
if not allind.all():
print("Some indices not used!")
#pdb.set_trace()
# Lambda^e and eta^d are more tricky:
# Simple cases:
lambdad[i01] = 0.
etad[i01] = 0.
if any06:
lambdad[i06] = 1./3. - 4./ninePi
etad[i06] = 0.09375 # = 3./32.
if any11:
lambdad[i11] = 1.
# etad[i11] = 1. # This is what the paper says
etad[i11] = 0.5 # Typo in paper (according to J. Eastman)
# Lambda_1:
ilam1 = i02 + i08
q1 = p2 - z2[ilam1]
## This is what the paper says:
#ellippi = ellpic_bulirsch(1. - 1./a[ilam1], k[ilam1])
# ellipe, ellipk = ellke(k[ilam1])
# This is what J. Eastman's code has:
# 2011-04-24 20:32 IJMC: The following codes act funny when
# sqrt((1-a)/(b-a)) approaches unity.
qq = np.sqrt((1. - a[ilam1]) / (b[ilam1] - a[ilam1]))
ellippi = ellpic_bulirsch(1./a[ilam1] - 1., qq)
ellipe, ellipk = ellke(qq)
lambdad[ilam1] = (1./ (ninePi*np.sqrt(p*z[ilam1]))) * \
( ((1. - b[ilam1])*(2*b[ilam1] + a[ilam1] - 3) - \
3*q1*(b[ilam1] - 2.)) * ellipk + \
4*p*z[ilam1]*(z2[ilam1] + 7*p2 - 4.) * ellipe - \
3*(q1/a[ilam1])*ellippi)
# Lambda_2:
ilam2 = i03 + i09
q2 = p2 - z2[ilam2]
## This is what the paper says:
#ellippi = ellpic_bulirsch(1. - b[ilam2]/a[ilam2], 1./k[ilam2])
# ellipe, ellipk = ellke(1./k[ilam2])
# This is what J. Eastman's code has:
ailam2 = a[ilam2] # Pre-cached for speed
bilam2 = b[ilam2] # Pre-cached for speed
omailam2 = 1. - ailam2 # Pre-cached for speed
ellippi = ellpic_bulirsch(bilam2/ailam2 - 1, np.sqrt((bilam2 - ailam2)/(omailam2)))
ellipe, ellipk = ellke(np.sqrt((bilam2 - ailam2)/(omailam2)))
lambdad[ilam2] = (2. / (ninePi*np.sqrt(omailam2))) * \
((1. - 5*z2[ilam2] + p2 + q2*q2) * ellipk + \
(omailam2)*(z2[ilam2] + 7*p2 - 4.) * ellipe - \
3*(q2/ailam2)*ellippi)
# Lambda_3:
#ellipe, ellipk = ellke(0.5/ k) # This is what the paper says
if any07:
ellipe, ellipk = ellke(0.5/ p) # Corrected typo (1/2k -> 1/2p), according to J. Eastman
lambdad[i07] = 1./3. + (16.*p*(2*p2 - 1.)*ellipe -
(1. - 4*p2)*(3. - 8*p2)*ellipk / p) / ninePi
# Lambda_4
#ellipe, ellipk = ellke(2. * k) # This is what the paper says
if any05:
ellipe, ellipk = ellke(2. * p) # Corrected typo (2k -> 2p), according to J. Eastman
lambdad[i05] = 1./3. + (2./ninePi) * (4*(2*p2 - 1.)*ellipe + (1. - 4*p2)*ellipk)
# Lambda_5
## The following line is what the 2002 paper says:
#lambdad[i04] = (2./(3*np.pi)) * (np.arccos(1 - 2*p) - (2./3.) * (3. + 2*p - 8*p2))
# The following line is what J. Eastman's code says:
if any04:
lambdad[i04] = (2./3.) * (np.arccos(1. - 2*p)/np.pi - \
(6./ninePi) * np.sqrt(p * (1.-p)) * \
(3. + 2*p - 8*p2) - \
float(p > 0.5))
# Lambda_6
if any10:
lambdad[i10] = -(2./3.) * (1. - p2)**1.5
# Eta_1:
ilam3 = ilam1 + i07 # = i02 + i07 + i08
z2ilam3 = z2[ilam3] # pre-cache for better speed
twoZilam3 = 2*z[ilam3] # pre-cache for better speed
#kappa0 = np.arccos((p2+z2ilam3-1)/(p*twoZilam3))
#kappa1 = np.arccos((1-p2+z2ilam3)/(twoZilam3))
#etad[ilam3] = \
# (0.5/np.pi) * (kappa1 + kappa0*p2*(p2 + 2*z2ilam3) - \
# 0.25*(1. + 5*p2 + z2ilam3) * \
# np.sqrt((1. - a[ilam3]) * (b[ilam3] - 1.)))
etad[ilam3] = \
(0.5/np.pi) * ((np.arccos((1-p2+z2ilam3)/(twoZilam3))) + (np.arccos((p2+z2ilam3-1)/(p*twoZilam3)))*p2*(p2 + 2*z2ilam3) - \
0.25*(1. + 5*p2 + z2ilam3) * \
np.sqrt((1. - a[ilam3]) * (b[ilam3] - 1.)))
# Eta_2:
etad[ilam2 + i04 + i05 + i10] = 0.5 * p2 * (p2 + 2. * z2[ilam2 + i04 + i05 + i10])
# We're done!
## The following are handy for debugging:
#term1 = (1. - c2) * lambdae
#term2 = c2*lambdad
#term3 = c2*(2./3.) * (p>z).astype(float)
#term4 = c4 * etad
# Lambda^e is easy:
lambdae = 1. - occultuniform(z, p)
F = 1. - ((1. - c2) * lambdae + \
c2 * (lambdad + (2./3.) * (p > z).astype(float)) - \
c4 * etad) / fourOmega
#pdb.set_trace()
if retall:
ret = F, lambdae, lambdad, etad
else:
ret = F
#pdb.set_trace()
return ret
def occultnonlin(z,p0, cn):
"""Nonlinear limb-darkening light curve; cf. Section 3 of Mandel & Agol (2002).
:INPUTS:
z -- sequence of positional offset values
p0 -- planet/star radius ratio
cn -- four-sequence. nonlinear limb darkening coefficients
:EXAMPLE:
::
# Reproduce Figure 2 of Mandel & Agol (2002):
from pylab import *
import transit
z = linspace(0, 1.2, 50)
cns = vstack((zeros(4), eye(4)))
figure()
for coef in cns:
f = transit.occultnonlin(z, 0.1, coef)
plot(z, f)
:SEE ALSO:
:func:`t2z`, :func:`occultnonlin_small`, :func:`occultuniform`, :func:`occultquad`
:NOTES:
Scipy is much faster than mpmath for computing the Beta and
Gauss hypergeometric functions. However, Scipy does not have
the Appell hypergeometric function -- the current version is
not vectorized.
"""
# 2011-04-15 15:58 IJC: Created; forking from occultquad
#import pdb
# Initialize:
cn0 = np.array(cn, copy=True)
z = np.array(z, copy=True)
F = np.ones(z.shape, float)
p = np.abs(p0) # Save the original input
# Test the simplest case (a zero-sized planet):
if p==0:
ret = np.ones(z.shape, float)
return ret
# Define useful constants:
c0 = 1. - np.sum(cn0)
# Row vectors:
c = np.concatenate(([c0], cn0))
n = np.arange(5, dtype=float)
# Column vectors:
cc = c.reshape(5, 1)
nn = n.reshape(5,1)
np4 = n + 4.
nd4 = n / 4.
twoOmega = 0.5*c[0] + 0.4*c[1] + c[2]/3. + 2.*c[3]/7. + 0.25*c[4]
a = (z - p)**2
b = (z + p)**2
am1 = a - 1.
bma = b - a
k = 0.5 * np.sqrt(-am1 / (z * p))
p2 = p**2
z2 = z**2
# Define the many necessary indices for the different cases:
i01 = (p > 0) * (z >= (1. + p))
i02 = (p > 0) * (z > (.5 + np.abs(p - 0.5))) * (z < (1. + p))
i03 = (p > 0) * (p < 0.5) * (z > p) * (z <= (1. - p)) # also contains Case 4
#i04 = (z==(1. - p))
i05 = (p > 0) * (p < 0.5) * (z == p)
i06 = (p == 0.5) * (z == 0.5)
i07 = (p > 0.5) * (z == p)
i08 = (p > 0.5) * (z >= np.abs(1. - p)) * (z < p)
i08a = (p == 1) * (z == 0)
i09 = (p > 0) * (p < 1) * (z > 0) * (z < (0.5 - np.abs(p - 0.5)))
i10 = (p > 0) * (p < 1) * (z == 0)
i11 = (p > 1) * (z >= 0.) * (z < (p - 1.))
iN = i02 + i08
iM = i03 + i09
# Compute N and M for the appropriate indices:
# (Use the slow, non-vectorized appellf1 function:)
myappellf1 = np.frompyfunc(appellf1, 6, 1)
N = np.zeros((5, z.size), float)
M = np.zeros((3, z.size), float)
if iN.any():
termN = myappellf1(0.5, 1., 0.5, 0.25*nn + 2.5, am1[iN]/a[iN], -am1[iN]/bma[iN])
N[:, iN] = ((-am1[iN])**(0.25*nn + 1.5)) / np.sqrt(bma[iN]) * \
special.beta(0.25*nn + 2., 0.5) * \
(((z2[iN] - p2) / a[iN]) * termN - \
special.hyp2f1(0.5, 0.5, 0.25*nn + 2.5, -am1[iN]/bma[iN]))
if iM.any():
termM = myappellf1(0.5, -0.25*nn[1:4] - 1., 1., 1., -bma[iM]/am1[iM], -bma[iM]/a[iM])
M[:, iM] = ((-am1[iM])**(0.25*nn[1:4] + 1.)) * \
(((z2[iM] - p2)/a[iM]) * termM - \
special.hyp2f1(-0.25*nn[1:4] - 1., 0.5, 1., -bma[iM]/am1[iM]))
# Begin going through all the cases:
# Case 1:
F[i01] = 1.
# Case 2: (Gauss and Appell hypergeometric functions)
F[i02] = 1. - (1. / (np.pi*twoOmega)) * \
(N[:, i02] * cc/(nn + 4.) ).sum(0)
# Case 3 : (Gauss and Appell hypergeometric functions)
F[i03] = 1. - (0.5/twoOmega) * \
(c0*p2 + 2*(M[:, i03] * cc[1:4]/(nn[1:4] + 4.)).sum(0) + \
c[-1]*p2*(1. - 0.5*p2 - z2[i03]))
#if i04.any():
# F[i04] = occultnonlin_small(z[i04], p, cn)
# print "Value found for z = 1-p: using small-planet approximation "
# print "where Appell F2 function will not otherwise converge."
#pdb.set_trace()
#F[i04] = 0.5 * (occultnonlin(z[i04]+p/2., p, cn) + occultnonlin(z[i04]-p/2., p, cn))
# Case 5: (Gauss hypergeometric function)
F[i05] = 0.5 + \
((c/np4) * special.hyp2f1(0.5, -nd4 - 1., 1., 4*p2)).sum() / twoOmega
# Case 6: Gamma function
F[i06] = 0.5 + (1./(np.sqrt(np.pi) * twoOmega)) * \
((c/np4) * special.gamma(1.5 + nd4) / special.gamma(2. + nd4)).sum()
# Case 7: Gauss hypergeometric function, beta function
F[i07] = 0.5 + (0.5/(p * np.pi * twoOmega)) * \
((c/np4) * special.beta(0.5, nd4 + 2.) * \
special.hyp2f1(0.5, 0.5, 2.5 + nd4, 0.25/p2)).sum()
# Case 8: (Gauss and Appell hypergeometric functions)
F[i08a] = 0.
F[i08] = -(1. / (np.pi*twoOmega)) * (N[:, i02] * cc/(nn + 4.) ).sum(0)
# Case 9: (Gauss and Appell hypergeometric functions)
F[i09] = (0.5/twoOmega) * \
(c0 * (1. - p2) + c[-1] * (0.5 - p2*(1. - 0.5*p2 - z2[i09])) - \
2*(M[:, i09] * cc[1:4] / (nn[1:4] + 4.)).sum(0))
# Case 10:
F[i10] = (2. / twoOmega) * ((c/np4) * (1. - p2)**(nd4 + 1.)).sum()
# Case 11:
F[i11] = 0.
# We're done!
return F
def modeltransit(params, func, per, t):
"""Model a transit light curve of arbitrary type to a flux time
series, assuming zero eccentricity and a fixed, KNOWN period.
:INPUTS:
params -- (5+N)-sequence with the following:
the time of conjunction for each individual transit (Tc),
the impact parameter (b = a cos i/Rstar)
the stellar radius in units of orbital distance (Rstar/a),
planet-to-star radius ratio (Rp/Rstar),
stellar flux (F0),
the limb-darkening parameters u1 and u2:
EITHER:
gamma1, gamma2 -- quadratic limb-darkening coefficients
OR:
c1, c2, c3, c4 -- nonlinear limb-darkening coefficients
OR:
Nothing at all (i.e., only 5 parameters).
func -- function to fit to data, e.g. transit.occultquad
per -- float. Orbital period, in days.
t -- numpy array. Time of observations.
"""
# 2011-05-22 16:14 IJMC: Created.
# 2011-05-24 10:52 IJMC: Inserted a check for cos(i) > 1
ecc = 0.
nparam = len(params)
if (params[1] * params[2]) > 1: # cos(i) > 1: impossible!
return -1
else:
z = t2z(params[0], per, (180./np.pi)*np.arccos(params[1]*params[2]), t, 1./params[2], 0.)
# Mask out secondary eclipses:
#z[abs(((t - params[0] + params[1]*.25)/per % 1) - 0.5) < 0.43] = 10.
#pdb.set_trace()
if len(params)>5:
model = params[4] * func(z, params[3], params[5::])
try: # Limb-darkened
model = params[4] * func(z, params[3], params[5::])
except: # Uniform-disk
model = params[4] * (1. - func(z, params[3]))
return model
def modeltransit_general(params, t, NL, NP=1, errscale=1, smallplanet=True, svs=None):
"""Model a transit light curve of arbitrary type to a flux time
series, assuming zero eccentricity.
:INPUTS:
params -- (6 + NL + NP + NS)-sequence with the following:
Tc, the time of conjunction for each individual transit,
P, the orbital period (in units of "t")
i, the orbital inclination (in degrees; 90 is edge-on)
R*/a, the stellar radius in units of orbital distance,
Rp/R*, planet-to-star radius ratio,
the NP polynomial coefficients to normalize the data.
EITHER:
F0 -- stellar flux _ONLY_ (set NP=1)
OR:
[p_1, p_2, ..., p_(NP)] -- coefficients for polyval, to be
used as: numpy.polyval([p_1, ...], t)
the NL limb-darkening parameters (cf. Claret+2011):
EITHER:
u -- linear limb-darkening (set NL=1)
OR:
a, b -- quadratic limb-darkening (set NL=2)
OR:
c, d -- root-square limb-darkening (set NL= -2)
where
I(mu) = 1 - c * (1 - mu) - d * (1 - mu^0.5)
OR:
a1, a2, a3, a4 -- nonlinear limb-darkening (set NL=4)
where
I(mu) = 1 - a1 * (1 - mu^0.5) - a2 * (1 - mu) - \
a3 * (1 - mu^1.5) - a4 * (1 - mu^2)
OR:
Nothing at all -- uniform limb-darkening (set NL=0)
the NS state vectors, passed in as 'svs'
t -- numpy array. Time of observations.
smallplanet : bool
This only matters if NL>2. If "smallplanet" is True, use
:func:`occultnonlin_small`. Otherwise, use
:func:`occultnonlin`
errscale : int
If certain conditions (see below) are met, the resulting
transit light curve is scaled by this factor. When fitting,
set errscale to a very large value (e.g., 1e6) to use as an
extremely crude hard-edged filter.
A better way would be to incorporate constrained fitting...
svs : None or list of 1D NumPy Arrays
State vectors, applied with coefficients as defined above. To
avoid degeneracies with the NP polynomial terms (especially
the constant offset term), it is preferable that the state
vectors are all mean-subtracted.
:NOTES:
If quadratic or linear limb-darkening (L.D.) is used, the sum of
the L.D. coefficients cannot exceed 1. If they do, this routine
normalizes the coefficients [g1,g2] to: g_i = g_i / (g1 + g2).
If "Rp/R*", or "R*/a" are < 0, they will be set to zero.
If "P" < 0.01, it will be set to 0.01.
If "inc" > 90, it will be set to 90.
"""
# 2012-04-30 03:41 IJMC: Created
# 2012-05-08 16:59 IJMC: NL can be negative (for root-square profiles)
# 2013-01-31 18:21 IJMC: Added 'errscale' option
# 2013-04-02 09:07 IJMC: Added 'svs' option
# 2013-04-18 10:22 IJMC: Apply penalty scaling in 'sqrt' case if
# coefficients give nonphysical intensity values.
ecc = 0.
longperi = 0.
if svs is None:
nsvs = 0
else:
if isinstance(svs, np.ndarray) and svs.ndim==1:
svs = svs.reshape(1, svs.size)
nsvs = len(svs)
nparam = len(params) - nsvs
verbose = False
tc, per, inc, ra, k = params[0:5]
if NP>0:
poly_params = params[5:5+NP]
else:
poly_params = [1]
pNL = np.abs(NL)
if pNL>0:
ld_params = params[5+NP:5+NP+pNL]
penalty_factor = 1.
# Enforce various normalization constraints:
if inc > 90:
inc = 90.
penalty_factor *= errscale
if per < 0.01:
per = 0.01
penalty_factor *= errscale
if k < 0:
k = 0.
penalty_factor *= errscale
if ra <= 0:
ra = 1e-6
penalty_factor *= errscale
# Enforce the constraint that cos(i) <= 1.
#print ("%1.5f "*4) % (tc, per, inc, ra)
z = t2z(tc, per, inc, t, 1./ra, ecc=ecc, longperi=longperi)
if NL!=0 and (sum(ld_params)>1 or sum(ld_params)<0):
penalty_factor *= errscale
if NL==0: # Uniform
model = occultuniform(z, k)
elif NL==2 or NL==1: # Quadratic or Linear
model = occultquad(z, k, ld_params, verbose=verbose)
elif NL==-2: # Root-square (i.e., nonlinear)
new_ld_params = [ld_params[1], ld_params[0], 0., 0.]
if smallplanet:
model = occultnonlin_small(z, k, new_ld_params)
else:
model = occultnonlin(z, k, new_ld_params)
elif NL==4 or NL==3: # Nonlinear
if smallplanet:
model = occultnonlin_small(z, k, ld_params)
else:
model = occultnonlin(z, k, ld_params)
model *= np.polyval(poly_params, t)
for ii in xrange(nsvs):
model += params[-ii-1] * svs[-ii-1]
model *= penalty_factor
return model
def modeleclipse(params, func, per, t):
"""Model an eclipse light curve of arbitrary type to a flux time
series, assuming zero eccentricity and a fixed, KNOWN period.
:INPUTS:
params -- (6-or-7)-sequence with the following:
the time of conjunction for each individual eclipse (Tc),
the impact parameter (b = a cos i/Rstar)
the stellar radius in units of orbital distance (Rstar/a),
planet-to-star radius ratio (Rp/Rstar),
eclipse depth (dimensionless),
stellar flux (F0),
orbital period (OPTIONAL!)
func -- function to fit to data; presumably :func:`transit.occultuniform`
per -- float.
Orbital period, OR
None, if period is included in params
t -- numpy array.
Time of observations (same units as Tc and per)
"""
# 2011-05-30 16:56 IJMC: Created from modeltransit()
# 2012-01-31 22:14 IJMC: Period can be included in parameters, for
# fitting purposes.
ecc = 0.
nparam = len(params)
if per is None:
per = params[6]
if (params[1] * params[2]) > 1: # cos(i) > 1: impossible!
return -1
else:
z = t2z(params[0], per, (180./np.pi)*np.arccos(params[1]*params[2]), t, 1./params[2], 0.)
# if len(params)>6:
# model = params[4] * func(z, params[3], params[6::])
try: # Limb-darkened
TLC = func(z, params[3], params[6::])
except: # Uniform-disk
TLC = (func(z, params[3]))
# Appropriately scale eclipse depth:
#pdb.set_trace()
model = params[5] * (1. - params[4] * (TLC ) / params[3]**2)
return model
def modellightcurve(params, t, tfunc=occultuniform, nlimb=0, nchan=0):
"""Model a full planetary light curve: transit, eclipse, and
(sinusoidal) phase variation. Accept independent eclipse and
transit times-of-center, but otherwise assume a circular orbit
(and thus symmetric transits and eclipses).
:INPUTS:
params -- (M+10+N)-sequence with the following:
OPTIONALLY:
sensitivity variations for each of M channels (e.g.,
SST/MIPS). This assumes the times in 't' are in the order
(T_{1,0}, ... T_{1,M-1}, ... T_{2,0}, ...). The parameters
affect the data multiplicatively as (1 + c_i), with the
constraint that Prod_i(1+c_i) = 1.
the time of conjunction for each individual transit (T_t),
the time of conjunction for each individual eclipse (T_e),
the orbital period (P),
the impact parameter (b = a cos i/Rstar)
the stellar radius in units of orbital distance (Rstar/a),
planet-to-star radius ratio (Rp/Rstar),
stellar flux (F0),
maximum (hot-side) planet flux (Fbright),
minimum (cold-side) planet flux (Fdark),
phase curve offset (phi_0; 0 implies maximum flux near eclipse)
OPTIONALLY:
limb-darkening parameters (depending on tfunc):
EITHER:
gamma1, gamma2 -- quadratic limb-darkening coefficients
OR:
c1, c2, c3, c4 -- nonlinear limb-darkening coefficients
t -- numpy array. Time of observations; same units as orbital
period and ephemerides. If nchan>0, t should
be of shape (nchan, L), or a .ravel()ed
version of that.
:OPTIONS:
tfunc : model transit function
One of :func:`occultuniform`, :func:`occultnonlin_small`,
:func:`occultquad`, or :func:`occultnonlin`
nlimb : int
number of limb-darkening parameters; these should be the last
values of params.
nchan : int
number of photometric channel sensitivity perturbations;
these should be the first 'nchan' values of params.
:EXAMPLE:
TBW
"""
# 2011-06-10 11:10 IJMC: Created.
# 2011-06-14 13:18 IJMC: Sped up with creation of z2dt()
# 2011-06-30 21:00 IJMC: Fixed functional form of phase curve.
from scipy import optimize
import pdb
ecc = 0.
if nchan>0:
cparams = params[0:nchan].copy()
params = params[nchan::].copy()
cparams[0] = 1./(1. + cparams[1::]).prod() - 1.
nparam = len(params)
tt, te, per, b, ra, k, fstar, fbright, fdark, phi = params[0:10]
if nparam > 10:
limbdarkening = params[10::]
else:
limbdarkening = None
cosi = b * ra
if (cosi) > 1: # cos(i) > 1: impossible!
return -1
else:
zt = t2z(tt, per, (180./np.pi)*np.arccos(b * ra), t, 1./ra, ecc)
ze = t2z(te, per, (180./np.pi)*np.arccos(b * ra), t, 1./ra, ecc)
inc = np.arccos(cosi)
# Solve for t given z0, such that z0 - t2z(t) = 0.
def residualz(tguess, z0):
return z0 - t2z(te, per, (180./np.pi)*np.arccos(b * ra), tguess, 1./ra, ecc)
# Mask out secondary eclipses:
#z[abs(((t - params[0] + params[1]*.25)/per % 1) - 0.5) < 0.43] = 10.
sep = (tt - te) % per
transit_times = (((t - tt) % per) < sep/2.) + (((t - tt) % per) > (per - sep/2.))
eclipse_times = (((t - te) % per) < sep/2.) + (((t - te) % per) > (per - sep/2.))
#pdb.set_trace()
# Model phase curve flux
def phaseflux(time):
return 0.5*(fbright + fdark) + \
0.5*(fbright - fdark) * np.cos((2*np.pi*(time - tt))/per + phi)
phas = phaseflux(t)
# Model transit:
trans = np.ones(zt.shape, dtype=float)
if limbdarkening is None:
trans[transit_times] = (1. - tfunc(zt[transit_times], k))
else:
trans[transit_times] = tfunc(zt[transit_times], k, limbdarkening)
transit_curve = trans*fstar + phas
# Model eclipse:
feclip = phaseflux(te) / (fstar + phaseflux(te))
eclip = np.ones(ze.shape, dtype=float)
eclip[eclipse_times] = (1. - occultuniform(ze[eclipse_times], k))
eclip = 1. + feclip * (eclip - 1.) / k**2
# A lot of hokey cheats to keep the eclipse bottom flat, but
# ingress and egress continuous:
## The following code is deprecated with the creation of z2dt()
#t14 = (per/np.pi) * np.arcsin(ra * np.sqrt((1. + k**2) - b**2)/np.sin(np.arccos(cosi)))
#t23 = (per/np.pi) * np.arcsin(ra * np.sqrt((1. - k**2) - b**2)/np.sin(np.arccos(cosi)))
#t12 = 0.5 * (t14 - t23)
#zzz = [t2z(tt, per, (180./np.pi)*np.arccos(b * ra), thist, 1./ra, ecc) for thist in [te-t14, te, te+t14]]
#aaa,bbb = residualz(te-t14, 1. + k), residualz(te, 1. + k)
#ccc,ddd = residualz(te-t14, 1. - k), residualz(te, 1. - k)
#if (aaa >= 0 and bbb >= 0) or (aaa <= 0 and bbb <= 0):
# print aaa, bbb
# print te, t14, t23, k, ra, b, per
# pdb.set_trace()
#if (ccc >= 0 and ddd >= 0) or (ccc <= 0 and ddd <= 0):
# print ccc, ddd
# print te, t14, t23, k, ra, b, per
# pdb.set_trace()
#pdb.set_trace()
#t5 = optimize.bisect(residualz, te - 2*t14, te + t14, args=(1. + k,))
##t5 = optimize.newton(residualz, te - t23 - t12, args=(1. + k,))
##pdb.set_trace()
##t6 = optimize.newton(residualz, te - t23 + t12, args=(1. - k,))
#t6 = optimize.bisect(residualz, te - 2*t14, te + t14, args=(1. - k,))
t5 = te - z2dt_circular(per, inc*180./np.pi, 1./ra, 1. + k)
t6 = te - z2dt_circular(per, inc*180./np.pi, 1./ra, 1. - k)
t7 = te + (te - t6)
t8 = te + (te - t5)
#z58 = [t2z(tt, per, (180./np.pi)*np.arccos(b * ra), thist, 1./ra, ecc) for thist in [t5,t6,t7,t8]]
eclipse_ingress = eclipse_times * (((t - t5) % per) < (t6 - t5))
if eclipse_ingress.any():
inscale = np.zeros(ze.shape, dtype=float)
tei = t[eclipse_ingress]
inscale[eclipse_ingress] = ((fstar + phaseflux(t6)) * (1. - feclip) - fstar) * \
((tei - tei.min()) / (tei.max() - tei.min()))
else:
inscale = 0.
eclipse_egress = eclipse_times * (((t - t7) % per) < (t8 - t7))
if eclipse_egress.any():
egscale = np.zeros(ze.shape, dtype=float)
tee = t[eclipse_egress]
egscale[eclipse_egress] = ((fstar + phaseflux(t7)) * (1. - feclip) - fstar) * \
((tee - tee.max()) / (tee.max() - tee.min()))
else:
egscale = 0.
# Now compute the full light curve:
full_curve = transit_curve * eclip
full_curve[eclipse_times * (ze < (1. - k))] = fstar
full_curve = full_curve - inscale + egscale
if nchan>0:
if len(t.shape)==2: # Data entered as 2D
full_curve *= (1. + cparams.reshape(nchan, 1))
else: # Data entered as 1D
full_curve = (full_curve.reshape(nchan, full_curve.size/nchan) * \
(1. + cparams.reshape(nchan, 1))).ravel()
return full_curve
def modeleclipse_simple(params, tparams, func, t):
"""Model an eclipse light curve of arbitrary type to a flux time
series, assuming zero eccentricity and a fixed, KNOWN orbit.
:INPUTS:
params -- (3)-sequence with eclipse parameters to FIT:
the time of conjunction for each individual eclipse (Tc),
eclipse depth (dimensionless),
stellar flux (F0),
tparams -- (4)-sequence of transit parameters to HOLD FIXED:
the impact parameter (b = a cos i/Rstar)
the stellar radius in units of orbital distance (Rstar/a),
planet-to-star radius ratio (Rp/Rstar),
orbital period (same units as Tc and t)
func -- function to fit to data; presumably :func:`transit.occultuniform`
t -- numpy array. Time of observations.
"""
# 2011-05-31 08:35 IJMC: Created anew, specifically for eclipses.
ecc = 0.
if (tparams[0] * tparams[1]) > 1: # cos(i) > 1: impossible!
return -1
else:
z = t2z(params[0], tparams[3], (180./np.pi)*np.arccos(tparams[0]*tparams[1]), \
t, 1./tparams[1], ecc=ecc)
# Uniform-disk occultation:
TLC = (func(z, tparams[2]))
# Appropriately scale eclipse depth:
model = params[2] * (1. + params[1] * (TLC - 1.) / tparams[2]**2)
return model
def modeleclipse_simple14(params, tparams, func, t):
"""Model an eclipse light curve of arbitrary type to a flux time
series, assuming zero eccentricity and a fixed, KNOWN orbit.
:INPUTS:
params -- (14+3)-sequence with eclipse parameters to FIT:
the multiplicative sensitivity effects (c0, ..., c13), which
affect each bit of data as (1. + c_j) * ... HOWEVER, to keep
these from becoming degenerate with the overall stellar flux
level, only 13 of these are free parameters: the first (c0)
will always be set such that the product PROD_j(1 + c_j) = 1.
the time of conjunction for each individual eclipse (Tc),
eclipse depth (dimensionless),
stellar flux (F0),
tparams -- (4)-sequence of transit parameters to HOLD FIXED:
the impact parameter (b = a cos i/Rstar)
the stellar radius in units of orbital distance (Rstar/a),
planet-to-star radius ratio (Rp/Rstar),
orbital period (same units as Tc and t)
func -- function to fit to data; presumably :func:`transit.occultuniform`
t -- numpy array. Time of observations.
Must either be of size (14xN), or if a 1D vector then
t.reshape(14, N) must correctly reformat the data into data
streams at 14 separate positions.
"""
# 2011-05-31 08:35 IJMC: Created anew, specifically for eclipses.
# Separate the c (sensitivity) and t (transit) parameters:
cparams = params[0:14].reshape(14, 1)
params = params[14::]
cparams[0] = 1./(1.+cparams[1::]).prod() - 1.
tis1D = False # we want "t" to be 2D
if len(t.shape)==1:
t = t.reshape(14, t.size/14)
tis1D = True # "t" is 1D
elif len(t.shape)>2:
print("t is of too high a dimension (>2)")
return -1
# Get the vanilla transit light curve:
model = modeleclipse_simple(params, tparams, func, t)
# Apply sensitivity calibrations:
model *= (1. + cparams)
if tis1D:
model = model.ravel()
return model
def modeltransit14(params, func, per, t):
"""Model a transit light curve of arbitrary type to a flux time
series, assuming zero eccentricity and a fixed, KNOWN period, and
assuming MIPS-type data with 14 separate sensitivity dependencies.
:INPUTS:
params -- (14+5+N)-sequence with the following:
the multiplicative sensitivity effects (c0, ..., c13), which
affect each bit of data as (1. + c_j) * ... HOWEVER, to keep
these from becoming degenerate with the overall stellar flux
level, only 13 of these are free parameters: the first (c0)
will always be set such that the product PROD_j(1 + c_j) = 1.
the time of conjunction for each individual transit (Tc),
the impact parameter (b = a cos i/Rstar)
the stellar radius in units of orbital distance (Rstar/a),
planet-to-star radius ratio (Rp/Rstar),
stellar flux (F0),
the limb-darkening parameters u1 and u2:
EITHER:
gamma1, gamma2 -- quadratic limb-darkening coefficients
OR:
c1, c2, c3, c4 -- nonlinear limb-darkening coefficients
OR:
Nothing at all (i.e., only 5 parameters).
func -- function to fit to data, e.g. transit.occultquad
per -- float. Orbital period, in days.
t -- numpy array. Time of observations.
Must either be of size (14xN), or if a 1D vector then
t.reshape(14, N) must correctly reformat the data into data
streams at 14 separate positions.
:SEE ALSO:
:func:`modeltransit`
"""
# 2011-05-26 13:37 IJMC: Created, from the 'vanilla' modeltransit.
# Separate the c (sensitivity) and t (transit) parameters:
cparams = params[0:14].reshape(14, 1)
tparams = params[14::]
cparams[0] = 1./(1.+cparams[1::]).prod() - 1.
tis1D = False # we want "t" to be 2D
if len(t.shape)==1:
t = t.reshape(14, t.size/14)
tis1D = True # "t" is 1D
elif len(t.shape)>2:
print("t is of too high a dimension (>2)")
return -1
# Get the vanilla transit light curve:
model = modeltransit(tparams, func, per, t)
if np.sum(model + 1)==0:
model = -np.ones(t.shape, dtype=float)
# Apply sensitivity calibrations:
model *= (1. + cparams)
if tis1D:
model = model.ravel()
return model
def mcmc_transit_single(flux, sigma, t, per, func, params, stepsize, numit, nstep=1, posdef=None, holdfixed=None):
"""MCMC for 5-parameter eclipse function of transit with KNOWN period
:INPUTS:
flux : 1D array
Contains dependent data
sigma : 1D array
Contains standard deviation (uncertainties) of flux data
t : 1D array
Contains independent data: timing info
per : scalar
Known orbital period (same units as t)
func : function
Function to model transit (e.g., transit.occultuniform)
params : 5+N parameters to be fit
[T_center, b, Rstar/a, Rp/Rstar, Fstar] + (limb-darkening parameters?)
#[Fstar, t_center, b, v (in Rstar/day), p (Rp/Rs)]
stepsize : 1D or 2D array
if 1D: array of 1-sigma change in parameter per iteration
if 2D: array of covariances for new parameters
numit : int
Number of iterations to perform
nstep : int
Saves every "nth" step of the chain
posdef : None, 'all', or sequences of indices.
Which elements should be restricted to positive definite?
If indices, it should be of the form (e.g.): [0, 1, 4]
holdfixed : None, or sequences of indices.
Which elements should be held fixed in the analysis?
If indices, it should be of the form (e.g.): [0, 1, 4]
:RETURNS:
allparams : 2D array
Contains all parameters at each step
bestp : 1D array
Contains best paramters as determined by lowest Chi^2
numaccept: int
Number of accepted steps
chisq: 1D array
Chi-squared value at each step
:REFERENCES:
Numerical Recipes, 3rd Edition (Section 15.8); Wikipedia
"""
# 2011-05-14 16:06 IJMC: Adapted from upsand phase curve routines;
# also adapting Agol et al. 2010's Spitzer
# work, and from K. Stevenson's MCMC
# example implementation.
# 2011-05-24 15:52 IJMC: testing the new 'holdfixed' option.
# 2011-11-02 22:08 IJMC: Now cast numit as int
import numpy as np
#Initial setup
numaccept = 0
nout = numit/nstep
bestp = np.copy(params)
params = np.copy(params)
original_params = np.copy(params)
numit = int(numit)
# Set indicated parameters to be positive definite:
if posdef=='all':
params = np.abs(params)
posdef = np.arange(params.size)
elif posdef is not None:
posdef = np.array(posdef)
params[posdef] = np.abs(params[posdef])
else:
posdef = np.zeros(params.size, dtype=bool)
# Set indicated parameters to be positive definite:
if holdfixed is not None:
holdfixed = np.array(holdfixed)
params[holdfixed] = np.abs(params[holdfixed])
else:
holdfixed = np.zeros(params.size, dtype=bool)
weights = 1./sigma**2
allparams = np.zeros((len(params), nout))
allchi = np.zeros(nout,float)
#Calc chi-squared for model type using current params
zmodel = modeltransit(params, func, per, t)
currchisq = (((zmodel - flux)**2)*weights).ravel().sum()
bestchisq = currchisq
#Run Metropolis-Hastings Monte Carlo algorithm 'numit' times
for j in range(numit):
#Take step in random direction for adjustable parameters
if len(stepsize.shape)==1:
nextp = np.random.normal(params,stepsize)
else:
nextp = np.random.multivariate_normal(params, stepsize)
nextp[posdef] = np.abs(nextp[posdef])
nextp[holdfixed] = original_params[holdfixed]
#COMPUTE NEXT CHI SQUARED AND ACCEPTANCE VALUES
zmodel = modeltransit(nextp, func, per, t)
nextchisq = (((zmodel - flux)**2)*weights).ravel().sum()
accept = np.exp(0.5 * (currchisq - nextchisq))
if (accept >= 1) or (np.random.uniform(0, 1) <= accept):
#Accept step
numaccept += 1
params = np.copy(nextp)
currchisq = nextchisq
if (currchisq < bestchisq):
#New best fit
bestp = np.copy(params)
bestchisq = currchisq
if (j%nstep)==0:
allparams[:, j/nstep] = params
allchi[j/nstep] = currchisq
return allparams, bestp, numaccept, allchi
def mcmc_transit_single14(flux, sigma, t, per, func, params, stepsize, numit, nstep=1, posdef=None, holdfixed=None):
"""MCMC for 5-parameter eclipse function of transit with KNOWN period
:INPUTS:
flux : 1D array
Contains dependent data
sigma : 1D array
Contains standard deviation (uncertainties) of flux data
t : 1D array
Contains independent data: timing info
per : scalar
Known orbital period (same units as t)
func : function
Function to model transit (e.g., transit.occultuniform)
params : 14+5+N parameters to be fit
[c0,...,c13] + [T_center, b, Rstar/a, Rp/Rstar, Fstar] + (limb-darkening parameters?)
stepsize : 1D or 2D array
If 1D: 1-sigma change in parameter per iteration
If 2D: covariance matrix for parameter changes.
numit : int
Number of iterations to perform
nstep : int
Saves every "nth" step of the chain
posdef : None, 'all', or sequences of indices.
Which elements should be restricted to positive definite?
If indices, it should be of the form (e.g.): [0, 1, 4]
holdfixed : None, or sequences of indices.
Which elements should be held fixed in the analysis?
If indices, it should be of the form (e.g.): [0, 1, 4]
:RETURNS:
allparams : 2D array
Contains all parameters at each step
bestp : 1D array
Contains best paramters as determined by lowest Chi^2
numaccept: int
Number of accepted steps
chisq: 1D array
Chi-squared value at each step
:REFERENCES:
Numerical Recipes, 3rd Edition (Section 15.8); Wikipedia
"""
# 2011-05-27 13:46 IJMC: Created
# 2011-06-23 13:26 IJMC: Now accepts 2D covariance stepsize inputs.
# 2011-11-02 22:09 IJMC: Cast numit as int
import numpy as np
#Initial setup
numaccept = 0
nout = numit/nstep
params = np.copy(params)
#params[0] = 1./(1.+params[1:14]).prod() - 1.
bestp = np.copy(params)
original_params = np.copy(params)
numit = int(numit)
# Set indicated parameters to be positive definite:
if posdef=='all':
params = np.abs(params)
posdef = np.arange(params.size)
elif posdef is not None:
posdef = np.array(posdef)
params[posdef] = np.abs(params[posdef])
else:
posdef = np.zeros(params.size, dtype=bool)
# Set indicated parameters to be held fixed:
if holdfixed is not None:
holdfixed = np.array(holdfixed)
params[holdfixed] = np.abs(params[holdfixed])
else:
holdfixed = np.zeros(params.size, dtype=bool)
weights = 1./sigma**2
allparams = np.zeros((len(params), nout))
allchi = np.zeros(nout,float)
#Calc chi-squared for model type using current params
zmodel = modeltransit14(params, func, per, t)
currchisq = (((zmodel - flux)**2)*weights).ravel().sum()
bestchisq = currchisq
print("zmodel [0,1,2]=", zmodel.ravel()[0:3])
print("Initial chisq is %5.1f" % currchisq)
#Run Metropolis-Hastings Monte Carlo algorithm 'numit' times
for j in range(numit):
#Take step in random direction for adjustable parameters
if len(stepsize.shape)==1:
nextp = np.random.normal(params,stepsize)
else:
nextp = np.random.multivariate_normal(params, stepsize)
nextp[posdef] = np.abs(nextp[posdef])
nextp[holdfixed] = original_params[holdfixed]
#nextp[0] = 1./(1. + nextp[1:14]).prod() - 1.
#COMPUTE NEXT CHI SQUARED AND ACCEPTANCE VALUES
zmodel = modeltransit14(nextp, func, per, t)
nextchisq = (((zmodel - flux)**2)*weights).ravel().sum()
accept = np.exp(0.5 * (currchisq - nextchisq))
if (accept >= 1) or (np.random.uniform(0, 1) <= accept):
#Accept step
numaccept += 1
params = np.copy(nextp)
currchisq = nextchisq
if (currchisq < bestchisq):
#New best fit
bestp = np.copy(params)
bestchisq = currchisq
if (j%nstep)==0:
allparams[:, j/nstep] = params
allchi[j/nstep] = currchisq
return allparams, bestp, numaccept, allchi
def mcmc_eclipse(flux, sigma, t, func, params, tparams, stepsize, numit, nstep=1, posdef=None, holdfixed=None):
"""MCMC for 3-parameter eclipse function with KNOWN orbit
:INPUTS:
flux : 1D array
Contains dependent data
sigma : 1D array
Contains standard deviation (uncertainties) of flux data
t : 1D array
Contains independent data: timing info
func : function
Function to model eclipse (e.g., :func:`transit.occultuniform`)
params : parameters to be fit:
EITHER:
[T_center, depth, Fstar]
OR:
[c0, ..., c13, T_center, depth, Fstar]
params : 4 KNOWN, CONSTANT orbital parameters
[b, Rstar/a, Rp/Rstar, period]
stepsize : 1D array
Array of 1-sigma change in parameter per iteration
numit : int
Number of iterations to perform
nstep : int
Saves every "nth" step of the chain
posdef : None, 'all', or sequences of indices.
Which elements should be restricted to positive definite?
If indices, it should be of the form (e.g.): [0, 1, 4]
holdfixed : None, or sequences of indices.
Which elements should be held fixed in the analysis?
If indices, it should be of the form (e.g.): [0, 1, 4]
:RETURNS:
allparams : 2D array
Contains all parameters at each step
bestp : 1D array
Contains best paramters as determined by lowest Chi^2
numaccept: int
Number of accepted steps
chisq: 1D array
Chi-squared value at each step
:REFERENCES:
Numerical Recipes, 3rd Edition (Section 15.8); Wikipedia
"""
# 2011-05-31 10:48 IJMC: Created from mcmc_transit
# 2011-11-02 17:14 IJMC: Now cast numit as int
import numpy as np
#Initial setup
if len(params) > 14:
modelfunc = modeleclipse_simple14
else:
modelfunc = modeleclipse_simple
numaccept = 0
nout = numit/nstep
bestp = np.copy(params)
params = np.copy(params)
original_params = np.copy(params)
numit = int(numit)
# Set indicated parameters to be positive definite:
if posdef=='all':
params = np.abs(params)
posdef = np.arange(params.size)
elif posdef is not None:
posdef = np.array(posdef)
params[posdef] = np.abs(params[posdef])
else:
posdef = np.zeros(params.size, dtype=bool)
# Set indicated parameters to be positive definite:
if holdfixed is not None:
holdfixed = np.array(holdfixed)
params[holdfixed] = np.abs(params[holdfixed])
else:
holdfixed = np.zeros(params.size, dtype=bool)
weights = 1./sigma**2
allparams = np.zeros((len(params), nout))
allchi = np.zeros(nout,float)
#Calc chi-squared for model type using current params
zmodel = modelfunc(params, tparams, func, t)
currchisq = (((zmodel - flux)**2)*weights).ravel().sum()
bestchisq = currchisq
#Run Metropolis-Hastings Monte Carlo algorithm 'numit' times
for j in range(numit):
#Take step in random direction for adjustable parameters
nextp = np.random.normal(params,stepsize)
nextp[posdef] = np.abs(nextp[posdef])
nextp[holdfixed] = original_params[holdfixed]
#COMPUTE NEXT CHI SQUARED AND ACCEPTANCE VALUES
zmodel = modelfunc(nextp, tparams, func, t)
nextchisq = (((zmodel - flux)**2)*weights).ravel().sum()
accept = np.exp(0.5 * (currchisq - nextchisq))
if (accept >= 1) or (np.random.uniform(0, 1) <= accept):
#Accept step
numaccept += 1
params = np.copy(nextp)
currchisq = nextchisq
if (currchisq < bestchisq):
#New best fit
bestp = np.copy(params)
bestchisq = currchisq
if (j%nstep)==0:
allparams[:, j/nstep] = params
allchi[j/nstep] = currchisq
return allparams, bestp, numaccept, allchi
#def t14(per, ars, p0,
#
#t14 = (per/np.pi) * np.arcsin(ra * np.sqrt((1. + k**2) - b**2)/np.sin(np.arccos(cosi)))
#t23 = (per/np.pi) * np.arcsin(ra * np.sqrt((1. - k**2) - b**2)/np.sin(np.arccos(cosi)))
def fiteclipse(data, sv, ords, tlc, edata=None, index=None, dotransit=True, dopb=True):
"""data: time series to fit using least-squares.
sv: state vectors (e.g., various instrumental parameters)
ords: orders to raise each sv vector to: e.g., [1, [1,2], 3]
tlc: eclipse light curve
edata: error on the data (for chisq ONLY! No weighted fits.)
index: array index to apply to data, sv, and tlc
dopb: do prayer-bead uncertainty analysis
dotransit: include tlc in the fitting; otherwise, leave it out.
"""
# 2012-01-05 11:25 IJMC: Created
import analysis as an
#Simple prayer-bead analysis routine (using matrix multiplication):
def pbanal(data, xmatrix):
nobs, ncoef = xmatrix.shape
solns = np.zeros((nobs, ncoef), float)
solns[0] = np.dot(np.linalg.pinv(xmatrix), data)
model = np.dot(xmatrix, solns[0])
residual = data - model
for ii in range(1, nobs):
fakedata = model + np.concatenate((residual[ii::], residual[0:ii]))
solns[ii] = np.dot(np.linalg.pinv(xmatrix), fakedata)
return solns
nobs = len(data)
if sv is None:
sv = np.ones((0, nobs))
else:
sv = np.array(sv, copy=False)
if sv.size>0 and sv.size==sv.shape[0]:
sv = sv.reshape(1, len(sv))
nsv = sv.shape[0]
if index is None:
index = np.ones(nobs, dtype=bool)
else:
index = np.array(index, copy=False)
if edata is None:
edata = np.ones(nobs)
elif not hasattr(edata, '__iter__'):
edata = np.tile(edata, nobs)
else:
edata = np.array(edata, copy=False)
if len(edata.shape)==1:
weights = np.diag(1./edata**2)
elif len(edata.shape)==2:
weights = 1./edata**2
xmat = np.ones((1, nobs), float)
if dotransit:
xmat = np.vstack((xmat, tlc))
for jj in range(nsv):
if hasattr(ords[jj], '__iter__'):
for ord in ords[jj]:
xmat = np.vstack((xmat, sv[jj]**ord))
else:
xmat = np.vstack((xmat, sv[jj]**ords[jj]))
xmat = xmat.transpose()
nparam = xmat.shape[1]
prayerbead = pbanal(np.log(data[index]), xmat[index])
if dotransit:
depth = prayerbead[0,1]
udepth = an.dumbconf(prayerbead[:, 1], .683, type='central', mid=prayerbead[0,1])[0]
else:
edepth, udepth = 0., 0.
model = np.exp(np.dot(xmat, prayerbead[0,:]))
mods = np.exp(np.array([(np.dot(xmat, prayerbead[ii,:])) for ii in range(index.sum())]))
chisq = ((np.diag(weights) * (data - model)**2)[index]).sum()
bic = chisq + nparam * np.log(index.sum())
return (depth, udepth), (chisq, bic), prayerbead, model, mods
def analyzetransit_general(params, NL, NP, time, data, weights=None, dopb=False, domcmc=False, gaussprior=None, ngaussprior=None, nsigma=4, maxiter=10, parinfo=None, nthread=1, nstep=2000, nwalker_factor=20, xtol=1e-12, ftol=1e-10, errscale=1e6, smallplanet=True, svs=None, verbose=False):
"""
Fit transit to data, and estimate uncertainties on the fit.
:INPUTS:
params : sequence
A guess at the best-fit model transit parameters, to be passed
to :func:`modeltransit_general`.
If 'svs' are passed in (see below), then params should have an
additional value concatenated on the end as the coefficient for
each state vector.
NL : int
number of limb-darkening parameters (cf. :func:`modeltransit_general`)
NP : int
number of normalizing polynomial coefficients
(cf. :func:`modeltransit_general`)
time : sequence
time values (e.g., BJD_TDB - BJD_0)
data : sequence
photometric values (i.e., the transit light curve) to be fit to.
weights : sequence
weights to the photometric values. If None, weights will be
set equal to the inverse square of the residuals to the
best-fit model. In either case, extreme outliers will be
de-weighted in the fitting process. This will not change the
values of the input 'weights'.
nsigma : scalar
Residuals beyond this value of sigma-clipped standard
deviations will be de-weighted.
dopb : bool
If True, run prayer-bead (residual permutation) error analysis.
domcmc : bool
If True, run Markov Chain Monte Carlo error analysis (requires EmCee)
nstep : int
Number of steps for EmCee MCMC run. This should be *at least*
several thousand.
errscale: scalar
See :func:`modeltransit_general`
smallplanet: bool
See :func:`modeltransit_general`
svs : None, or sequence of 1D NumPy arrays
State vectors, for additional decorrelation of data in a
least-squares sense. See :func:`modeltransit_general`
:OUTPUTS:
(eventually, some object with useful fields)
:SEE_ALSO:
:func:`modeltransit_general`
"""
# 2012-05-03 11:42 IJMC: Created
# 2012-05-08 16:59 IJMC: Added ngaussprior option; NL can be negative.
# 2013-04-01 09:38 IJMC: Added 'svs' option; rejiggered errscale, smallplanet
# 2013-04-18 12:16 IJMC: Made this a bit smarter; now if MCMC
# sampler finds a new best fit,
# optimization is re-run and the sampler is
# restarted.
import emcee
#from kapteyn import kmpfit
#import transit
from scipy import optimize
import Crossfield_analysis as an
import Crossfield_phasecurves as pc
# Parse inputs:
bestparams = np.array(params, copy=True)
nparams = len(params)
if parinfo is None:
parinfo = [None] * nparams
if gaussprior is None:
gaussprior = [None] * nparams
fitkw = dict(gaussprior=gaussprior, ngaussprior=ngaussprior)
nobs = len(data)
# Run through an initial fitting routine, to flag and de-weight outliers:
goodind = np.isfinite(data)
prev_ngood = goodind.sum()
newBadPixels = True
niter = 0
if weights is None:
weights = np.ones(nobs) / data[goodind].var()
weights[True - goodind] = 1e-18
scaleWeights = True
else:
weights = np.array(weights, copy=True)
scaleWeights = False
while newBadPixels and niter <= maxiter:
fitargs = (transit.modeltransit_general, time, NL, NP, errscale, smallplanet, svs, data, weights, fitkw)
mod = transit.modeltransit_general(bestparams, *fitargs[1:-3])
# If using scipy.optimize:
lsq_fit = optimize.leastsq(pc.devfunc, bestparams, args=fitargs, full_output=True, xtol=xtol, ftol=ftol)
bestparams = lsq_fit[0]
covar = lsq_fit[1]
bestchisq = pc.errfunc(bestparams, *fitargs)
if covar is not None:
p0 = np.random.multivariate_normal(bestparams, 4*covar, 50)
testfits = [optimize.leastsq(pc.devfunc, pp, args=fitargs, full_output=True, xtol=xtol, ftol=ftol) for pp in p0]
testchi = [pc.errfunc(thisfit[0], *fitargs) for thisfit in testfits]
if min(testchi) < bestchisq:
if verbose: print("Optimizer found a better fit...")
bestchisq = min(testchi)
bestparams = testfits[testchi.index(bestchisq)][0]
covar = testfits[testchi.index(bestchisq)][1]
niter -= 1
# If using kapteyn.kmpfit:
#fitter = kmpfit.Fitter(residuals=pc.devfunc, data=fitargs)
#fitter.parinfo = parinfo
#fitter.fit(params0=params)
#params = fitter.params
#bestchisq = fitter.chi2_min
model = transit.modeltransit_general(bestparams, *fitargs[1:-3])
residuals = data - model
goodind = goodind * (True - (np.abs(residuals / an.stdr(residuals[goodind], nsigma=4)) > 4))
ngood = goodind.sum()
if scaleWeights:
weights = np.ones(nobs) / residuals[goodind].var()
weights[True - goodind] = 1e-18
if ngood==prev_ngood:
newBadPixels = False
else:
newBadPixels = True
prev_ngood = ngood
niter += 1
# Redefine fitting arguments, with outliers de-weighted:
fitargs = (transit.modeltransit_general, time, NL, NP, errscale, smallplanet, svs, data, weights, fitkw)
# Now run a prayer-bead analysis.
if dopb:
print("Starting prayer-bead analysis")
pb_fits = an.prayerbead(params, *fitargs, parinfo=parinfo, xtol=xtol)
#pb_eparams = np.array([an.dumbconf(pb_fits[:,ii], .683, mid=bestparams[ii])[0] for ii in range(len(bestparams))])
#pbchisq = [pc.errfunc(par0, *fitargs[:-1]) for par0 in pb_fits]
#pbmodels = [fitargs[0](par0, *fitargs[1:-3]) for par0 in pb_fits]
bestparams = pb_fits[0].copy()
else:
pb_fits = None
# Now run an MCMC analysis:
if domcmc:
print("Starting MCMC analysis")
ndim = len(params)
nwalkers = nwalker_factor * ndim
# Initialize sampler:
sampler = emcee.EnsembleSampler(nwalkers, ndim, pc.lnprobfunc, args=fitargs, threads=nthread)
if covar is None and dopb: # leastsq didn't work as advertised!
covar = np.cov(pb_fits.transpose())
elif covar is None: # ... and we don't even have a good estimator!
covar = np.zeros((nparams, nparams), dtype=float)
for ii in range(nparams):
if gaussprior[ii] is None:
covar[ii,ii] = (bestparams[ii]/100.)**2
else:
covar[ii,ii] = gaussprior[ii][1]**2
# Pick walker starting positions, excluding bad points:
p0 = np.random.multivariate_normal(bestparams, covar, nwalkers*5)
badp0 = ((p0[:,1] < 0) + (p0[:,2] < 0) + (p0[:,3] < 0) + (p0[:,4] < 0) + p0[:,2] > 90)
p0 = np.vstack((bestparams, p0[np.nonzero(True-badp0)[0][0:nwalkers-1]]))
# Run burn-in; exclude and remove bad walkers:
pos = p0
for ii in range(2):
pos, prob, state = sampler.run_mcmc(pos, max(1, (ii+1)*nstep/5))
if (bestchisq + 2*max(prob)) > ftol: #-2*prob < bestchisq).any(): # Found a better fit! Optimize:
if verbose: print("Found a better fit; re-starting MCMC... (%1.8f, %1.8f)" % (bestchisq, (bestchisq + 2*max(prob))))
#pdb.set_trace()
bestparams = pos[(prob==prob.max()).nonzero()[0][0]].copy()
lsq_fit = optimize.leastsq(pc.devfunc, bestparams, args=fitargs, full_output=True, xtol=xtol, ftol=ftol)
bestparams = lsq_fit[0]
covar = lsq_fit[1]
bestchisq = pc.errfunc(bestparams, *fitargs)
ii = 0 # Re-start the burn-in.
#pos[prob < np.median(prob)] = bestparams
pos[pos[:,2]>90,2] = pos[pos[:,2]>90,2] % 360.
pos[pos[:,2]>90,2] = 180 - pos[pos[:,2]>90,2] # reset inclination
badpos = (prob < np.median(prob))
if (pos[True-badpos].std(0) <= 0).any():
goodpos_unc = np.vstack((np.abs(bestparams / 100.), pos[True-badpos].std(0))).max(0)
pos[badpos] = np.random.normal(bestparams, goodpos_unc, (badpos.sum(), ndim))
else:
pos[badpos] = np.random.multivariate_normal(bestparams, np.cov(pos[True-badpos].transpose()), badpos.sum())
pos[badpos] = bestparams
# Run main MCMC run:
#pdb.set_trace()
pos, prob, state = sampler.run_mcmc(pos, max(1, (ii+1)*nstep/4))
sampler.reset()
steps_taken = 0
while steps_taken < nstep:
pos, prob, state = sampler.run_mcmc(pos, 1)
steps_taken += 1
if (bestchisq + 2*max(prob)) > ftol: # Found a better fit! Optimize:
if verbose: print("Found a better fit; re-starting MCMC... (%1.8f, %1.8f)" % (bestchisq, (bestchisq + 2*max(prob))))
#pdb.set_trace()
bestparams = pos[(prob==prob.max()).nonzero()[0][0]].copy()
lsq_fit = optimize.leastsq(pc.devfunc, bestparams, args=fitargs, full_output=True, xtol=xtol, ftol=1e-10)
bestparams = lsq_fit[0]
covar = lsq_fit[1]
bestchisq = pc.errfunc(bestparams, *fitargs)
steps_taken = 0 # Re-start the MCMC
sampler.reset()
pos[prob<np.median(prob)] = bestparams
# Test if MCMC found a better chi^2 region of parameter space:
mcmc_params = sampler.flatchain[np.nonzero(sampler.lnprobability.ravel()==sampler.lnprobability.ravel().max())[0][0]]
mcmc_fit = optimize.leastsq(pc.devfunc, mcmc_params, args=fitargs, full_output=True, xtol=xtol, ftol=1e-10)
if pc.errfunc(mcmc_fit[0], *fitargs) < pc.errfunc(bestparams, *fitargs):
bestparams = mcmc_fit[0]
else:
pass
else:
sampler = None
# Run a second fit w/Kapteyn:
#fitter2 = kmpfit.Fitter(residuals=pc.devfunc, data=fitargs)
#fitter2.parinfo = parinfo
#fitter2.fit(params0=mcmc_params)
#bestparams = fitter2.params
#model2 = transit.modeltransit_general(bestparams, *fitargs[1:-2])
# Run a second fit with scipy.optimize.leastsq:
lsq_fit = optimize.leastsq(pc.devfunc, bestparams, args=fitargs, full_output=True, xtol=xtol, ftol=1e-10)
bestparams = lsq_fit[0]
covar = lsq_fit[1]
bestchisq = pc.errfunc(bestparams, *fitargs)
finalmodel = transit.modeltransit_general(bestparams, *fitargs[1:-3])
return lsq_fit, pb_fits, sampler, weights, finalmodel
| 85,453 | 32.696372 | 289 | py |
Namaste | Namaste-master/namaste/namaste.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
:py:mod:`Namaste.py` - Single transit fitting code
-------------------------------------
'''
import autograd.numpy as np2
import matplotlib
#matplotlib.use('Agg')
import pylab as plt
plt.ioff()
import scipy.optimize as optimize
from os import sys, path
import datetime
import logging
import pandas as pd
import emcee
import celerite
from .planetlib import *
from .Crossfield_transit import *
from scipy import stats
import scipy.optimize as opt
import pickle
import autograd.numpy.numpy_boxes
import os
Namwd = path.dirname(path.realpath(__file__))
logger = logging.getLogger('namaste')
logger.setLevel(level=logging.DEBUG)
fh = logging.FileHandler(filename=Namwd+'/namaste_runlog.log')
fh.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(lineno)d:%(filename)s(%(process)d) - %(message)s'))
logger.addHandler(fh)
#logger.basicConfig(filename=Namwd+'/namaste_runlog.log', level=logger.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
#logger = logger.getLogger(__name__)
#How best to do this...
#
# make lightcurve a class
# make candidate a class
# make star a class
# make planet a class
# Give candidate a star and planet and lightcurve
# Use the planet to generate the lightcurve model
# Use the star to generate priors
# Give candidate data in the form of a lightcurve - can switch out for CoRoT, Kepler, etc.
class Settings():
'''
The class that contains the model settings
'''
def __init__(self, **kwargs):
self.GP = True # GP on/off
self.nopt = 25 # Number of optimisation steps for each GP and mono before mcmc
self.nsteps = 12500 # Number of MCMC steps
self.npdf = 6000 # Number of samples in the distributions from which to doing calcs.
self.nwalkers = 24 # Number of emcee walkers
self.nthreads = 8 # Number of emcee threads
self.ndurswindow = 6 # Number of Tdurs either side of the transit to be fitted.
self.anomcut = 3.75 # Number of sigma above/below to count as an outlier.
#self.binning = -1 # Days to bin to. -1 dictates no bin
#self.error = False # No error detected
#self.error_comm = '' # Error description
#self.use_previous_samples = False# Using samaples from past run
self.fitsloc = './InputFiles/' # Storage location to load stuff
self.outfilesloc = './Outputs/' # Storage location to save stuff
self.cadence = 0.0204318 # Cadence. Defaults to K2
self.kernel = 'quasi' # Kernel for use in GPs
self.verbose = True # Print statements or not...
self.mission = 'K2' # Mission
self.fit_tdur = False # Use Tdur, rather than velocity, to perform fits
self.fit_vel = True # Use velocity, rather than Tdur, to perform fits
self.update_logger()
def update_logger(self):
if self.verbose and logging.StreamHandler not in [type(hand) for hand in logger.handlers]:
sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(lineno)d:%(filename)s(%(process)d) - %(message)s'))
logger.addHandler(sh)
elif not self.verbose:
logger.setLevel(level=logging.WARNING)
def update(self, **kwargs):
'''
Adding new settings...
'''
self.GP = kwargs.pop('GP', self.GP)
self.nopt = kwargs.pop('nopt', self.nopt)
self.nsteps = kwargs.pop('nsteps', self.nsteps)
self.npdf = kwargs.pop('npdf', self.npdf)
self.nwalkers = kwargs.pop('nwalkers', self.nwalkers)
self.nthreads = kwargs.pop('nthreads', self.nthreads)
self.ndurswindow = kwargs.pop('ndurswindow', self.ndurswindow)
self.anomcut = kwargs.pop('anomcut', self.anomcut)
#self.binning = kwargs.pop('binning', self.binning)
#self.error = kwargs.pop('error', self.binning)
#self.error_comm = kwargs.pop('error_comm', self.binning)
#self.use_previous_samples = kwargs.pop('use_previous_samples', self.binning)
self.fitsloc = kwargs.pop('fitsloc', self.fitsloc)
self.outfilesloc = kwargs.pop('outfilesloc', self.outfilesloc)
self.cadence = kwargs.pop('cadence', self.cadence)
self.kernel = kwargs.pop('kernel', self.kernel)
self.verbose = kwargs.pop('verbose', self.verbose)
if 'verbose' in kwargs:
self.update_logger()
self.mission = kwargs.pop('mission', self.mission)
self.fit_tdur = kwargs.pop('fit_tdur', self.fit_tdur)
self.fit_vel = kwargs.pop('fit_vel', self.fit_vel)
def printall(self):
print(vars(self))
class Star():
def __init__(self, name, settings):
logger.info(name+' - initialising Star object')
self.objname = str(name)
self.settings = settings
#Initialising lists of monotransits and multi-pl
self.meanmodels=[] #list of mean models to fit.
self.fitdict={} #dictionary of model parameter PDFs to fit
def exofop_dat(self):
#Getting information from exofop...
logger.info(self.objname+' - Getting information from exofop')
sdic=ExoFop(int(self.objname))
if 'radius' in sdic.columns:
self.addRad(sdic['radius'],sdic['radius_err'],np.max([sdic['radius']*0.8,sdic['radius_err']]))
else:
raise ValueError("No radius")
if 'teff' in sdic.columns:
self.addTeff(sdic['teff'],sdic['teff_err'],sdic['teff_err'])
else:
raise ValueError("No teff")
if 'mass' in sdic.columns:
self.addMass(sdic['mass'],sdic['mass_err'],sdic['mass_err'])
else:
raise ValueError("No mass")
if 'logg' in sdic.columns:
self.addlogg(sdic['logg'],sdic['logg_err'],sdic['logg_err'])
if 'feh' in sdic.columns:
self.addfeh(sdic['feh'],sdic['feh_err'],sdic['feh_err'])
if 'density' in sdic.columns:
self.addDens(sdic['density'],sdic['density_err'],sdic['density_err'])
else:
self.addDens()
def csvfile_dat(self,file,errorstyle=['ep','em']):
#Collecting from CSV file, eg Best_Stellar_Params_nogriz
logger.info(self.objname+' - Getting information from csv')
if type(file) is not pd.DataFrame and type(file) is not pd.Series:
df=pd.DataFrame.from_csv(file)
if df.shape[1]==1:
#1D file:
row=df.T
else:
row=df.loc[df.epic==int(self.objname)]
csvname=row.index.values[0]
row=row.T.to_dict()[csvname]
self.addRad(row['rad'],row['rad'+errorstyle[0]],row['rad'+errorstyle[1]])
self.addTeff(row['teff'],row['teff'+errorstyle[0]],row['teff'+errorstyle[1]])
self.addMass(row['mass'],row['mass'+errorstyle[0]],row['mass'+errorstyle[1]])
self.addlogg(row['logg'],row['logg'+errorstyle[0]],row['logg'+errorstyle[1]])
self.addfeh(row['feh'],row['feh'+errorstyle[0]],row['feh'+errorstyle[1]])
if not pd.isnull(row['rho']):
self.addDens(row['rho'],row['rho'+errorstyle[0]],row['rho'+errorstyle[1]])
else:
self.addDens()
#avs avsem avsep dis disem disep epic feh fehem fehep input 2MASS input BV
#input SDSS input_spec logg loggem loggep lum lumem lumep mass massem massep
#n_mod prob rad radem radep rank realspec rho rho_err rhoem rhoep teff teffem teffep
def addTeff(self,val,uerr,derr=None):
self.steff = float(val)
self.steffuerr = float(uerr)
self.steffderr = self.steffuerr if type(derr)==type(None) else float(derr)
def addRad(self,val,uerr,derr=None):
self.srad = float(val)
self.sraduerr = float(uerr)
self.sradderr = self.sraduerr if type(derr)==type(None) else float(derr)
def addMass(self,val,uerr,derr=None):
self.smass = float(val)
self.smassuerr = float(uerr)
self.smassderr = self.smassuerr if type(derr)==type(None) else float(derr)
def addlogg(self,val,uerr,derr=None):
self.slogg = float(val)
self.slogguerr = float(uerr)
self.sloggderr = self.slogguerr if type(derr)==type(None) else float(derr)
def addfeh(self,val,uerr,derr=None):
self.sfeh = float(val)
self.sfehuerr = float(uerr)
self.sfehderr = self.sfehuerr if type(derr)==type(None) else float(derr)
def addDens(self,val=None,uerr=None,derr=None):
if val==None:
sdenss=CalcDens(self,returnpost=False)#[self.teff,self.steffuerr,self.steffderr,self.srad,self.sraduerr,self.sradderr,
pctns=np.percentile(sdenss,[15.865525393145707, 50.0, 84.13447460685429])
self.sdens=pctns[1]
self.sdensuerr=pctns[2]-pctns[1]
self.sdensderr=pctns[1]-pctns[0] #self.smass,self.smassuerr,self.smassderr,self.slogg,self.slogguerr,self.sloggderr])
else:
#Density defined by others
if float(val)>200:
#Normalising to Solar density:
val=float(val)/1410.0;uerr=float(uerr)/1410.0;derr=float(derr)/1410.0
else:
val=float(val);uerr=float(uerr);derr=float(derr)
self.sdens = float(val)
self.sdensuerr = float(uerr)
self.sdensderr = self.sdensuerr if type(derr)==type(None) else float(derr)
def addLightcurve(self,file):
self.Lcurve=Lightcurve(file,self.objname,self.settings)
self.mag=self.Lcurve.mag
if self.settings.mission=="kepler" or self.settings.mission=='k2':
self.wn=2.96e-4/np.sqrt(10**((14-self.mag)/2.514)) #2.42e-4 is the White Noise at 14th magnitude for Kepler.
else:
self.wn=np.percentile(abs(np.diff(self.Lcurve.lc[:,1])),40) #Using 40th percentile of the absolute differences.
return self.Lcurve
def EstLimbDark(self):
if not hasattr(self,'sloggs'):
self.PDFs()
if self.settings.mission=="kepler" or self.settings.mission=='k2':
LDs=getKeplerLDs(self.steffs,logg=self.sloggs,FeH=self.sfeh)
elif self.settings.mission=="TESS":
#logger.error("TESS not yet supported")
raise ValueError("TESS not yet supported")
else:
#assume mission==Kepler
LDs=getKeplerLDs(self.steffs,logg=self.sloggs,FeH=self.sfeh)
pctns=np.percentile(LDs[0],[15.865525393145707, 50.0, 84.13447460685429])
self.LD1s=LDs[:,0]
self.LD1=pctns[1]
self.LD1uerr=pctns[2]-pctns[1]
self.LD1derr=pctns[1]-pctns[0]
pctns=np.percentile(LDs[1],[15.865525393145707, 50.0, 84.13447460685429])
self.LD2s=LDs[:,1]
self.LD2=pctns[1]
self.LD2uerr=pctns[2]-pctns[1]
self.LD2derr=pctns[1]-pctns[0]
self.initLD()
def PDFs(self):
if hasattr(self,'steff')*hasattr(self,'steffuerr')*hasattr(self,'steffderr'):
self.steffs=noneg_GetAssymDist(self.steff,self.steffuerr,self.steffderr,nd=self.settings.npdf)
if hasattr(self,'srad')*hasattr(self,'sraduerr')*hasattr(self,'sradderr'):
self.srads =noneg_GetAssymDist(self.srad,self.sraduerr,self.sradderr,nd=self.settings.npdf)
if hasattr(self,'smass')*hasattr(self,'smassuerr')*hasattr(self,'smassderr'):
self.smasss=noneg_GetAssymDist(self.smass,self.smassuerr,self.smassderr,nd=self.settings.npdf)
if hasattr(self,'slogg')*hasattr(self,'slogguerr')*hasattr(self,'sloggderr'):
self.sloggs=GetAssymDist(self.slogg,self.slogguerr,self.sloggderr,nd=self.settings.npdf,returndist=True)
elif hasattr(self,'srads')*hasattr(self,'smasss'):
self.sloggs=np.log10(self.smasss/self.srads)+4.44
#GetAssymDist(self.slogg,self.slogguerr,self.sloggderr,nd=self.settings.npdf,returndist=True)
if hasattr(self,'sdens')*hasattr(self,'sdensuerr')*hasattr(self,'sdensderr'):
self.sdenss=noneg_GetAssymDist(self.sdens,self.sdensuerr,self.sdensderr,nd=self.settings.npdf)
#Adding sfeh if necessary
if not hasattr(self,'sfeh'):
self.sfeh=0.0
def pdflist(self):
if not hasattr(self,'steffs'):
self.PDFs()
if not hasattr(self,'LD1s'):
self.EstLimbDark()
return {'steffs':self.steffs,'srads':self.srads,'smasss':self.smasss,'sloggs':self.sloggs,'sdenss':self.sdenss,\
'LD1s':self.LD1s,'LD2s':self.LD2s}
def addGP(self,vector=None,overwrite=True):
logger.info(self.objname+' - Adding GP')
if self.settings.GP and (not hasattr(self, 'kern') or overwrite):
if self.settings.kernel=='Real':
self.kern=celerite.terms.RealTerm(log_a=np.log(np.var(self.Lcurve.lc[:,1])), log_c=-np.log(3.0),
bounds={'log_a':(-20,0.0),'log_c':(-3,4.5)})+\
celerite.terms.JitterTerm(np.log(self.wn),bounds=dict(log_sigma=(np.log(self.wn)-0.25,np.log(self.wn)+0.25)))
if vector is not None:
self.kern.set_parameter_vector(vector)
self.kern.freeze_parameter('terms[1]:log_sigma') # and freezing white noise
elif self.settings.kernel=='quasi':
self.kern= RotationTerm(np.log(np.var(self.Lcurve.lc[:,1])), np.log(0.25*self.Lcurve.range), np.log(2.5), 0.0,
bounds=dict(
log_amp=(-20.0, -2.0),
log_timescale=(np.log(1.5), np.log(5*self.Lcurve.range)),
log_period=(np.log(1.2), np.log(2*self.Lcurve.range)),
log_factor=(-5.0, 5.0),
)
)+\
celerite.terms.JitterTerm(np.log(self.wn),
bounds=dict(
log_sigma=(np.log(self.wn)-0.25,np.log(self.wn)+0.25)
)
)
if vector is not None:
self.kern.set_parameter_vector(vector)
logger.info(self.objname+' - GP is '+' , '.join(list(self.kern.get_parameter_vector().astype(str))))
#self.initgp={'log_amp':,'log_timescale':,'log_period':,'log_factor':,'log_sigma':}
self.kern.freeze_parameter('terms[0]:log_factor') # freezing log factor
self.kern.freeze_parameter('terms[1]:log_sigma') # and freezing white noise
self.initgp={itrm:self.kern.get_parameter(itrm) for itrm in self.kern.get_parameter_names()}
elif self.settings.GP:
self.initgp={itrm:self.kern.get_parameter(itrm) for itrm in self.kern.get_parameter_names()}
else:
self.kern = None
self.initgp = None
def Optimize_GP(self):
#Optimizing initial GP parameters, depending on GP supplied...
'''
#This optimizes the gaussian process on out-of-transit data. This is then held with a gaussian prior during modelling
'''
if not self.settings.GP:
self.fitdict={}
raise ValueError("GP is set as False.")
logger.info(self.objname+' - optimizing GP')
import scipy.optimize as op
#Cutting transits from lc
self.Lcurve.calc_mask(self.meanmodels)
lc_trn=self.Lcurve.lc[self.Lcurve.lcmask]
#logger.debug(self.objname+' - mask: '+','.join(self.Lcurve.lcmask.astype(str)))
logger.debug(self.objname+' - nans in y: '+str(np.sum(np.isnan(lc_trn[:,1]))))
lc_trn[:,1]/=np.nanmedian(lc_trn[:,1])#This half may be different in median from the full lc, so adjusting for this...
if not hasattr(self,'gp'):
self.addGP()
self.kern.thaw_all_parameters()
gp_notr=celerite.GP(kernel=self.kern,mean=1.0,fit_mean=True)
gp_notr.compute(lc_trn[:,0],lc_trn[:,2])
#logger.debug(self.objname+' - y: '+','.join(lc_trn[:,1].astype(str)))
logger.debug(self.objname+' - vect: '+','.join(gp_notr.get_parameter_vector().astype(str)))
logger.debug(self.objname+' - bounds: '+' , '.join(['('+str(b[0])+' | '+str(b[1])+')' for b in gp_notr.get_parameter_bounds()]))
logger.debug(self.objname+' - nll: '+str(neg_log_like(gp_notr.get_parameter_vector(),lc_trn[:,1],gp_notr)))
#Initial results:
init_res=op.minimize(neg_log_like, list(gp_notr.get_parameter_vector()), args=(lc_trn[:,1],gp_notr),jac=grad_neg_log_like)#, method="L-BFGS-B")#,jac=grad_neg_log_like)
logger.debug(self.objname+' - init GP lpp is '+str(init_res.fun)+' using '+' , '.join(list(init_res.x.astype(str))))
fails=0
if self.settings.kernel=='quasi':
# Run the optimization routine for a grid of size self.settings.nopt
#log_amp, log_timescale, log_period, log_factor, log_sigma, mean = params
iterparams= np.column_stack((np.random.normal(gp_notr.kernel.get_parameter_vector()[0],3.0,self.settings.nopt),
np.random.uniform(1.2,np.log(1.5*self.Lcurve.range),self.settings.nopt),
np.random.uniform(np.log(6*self.settings.cadence),np.log(1.5*self.Lcurve.range),self.settings.nopt),
np.tile(0.0,self.settings.nopt),
np.tile(np.log(self.wn),self.settings.nopt),
np.tile(1.0,self.settings.nopt)))
elif self.settings.kernel=='Real':
#log_a, log_c = params
iterparams=np.column_stack((np.random.normal(gp_notr.kernel.get_parameter_vector()[0],np.sqrt(abs(gp_notr.kernel.get_parameter_vector()[0])),self.settings.nopt),
np.random.normal(gp_notr.kernel.get_parameter_vector()[1],np.sqrt(abs(gp_notr.kernel.get_parameter_vector()[1])),self.settings.nopt),
np.tile(np.log(self.wn),self.settings.nopt),
np.tile(1.0,self.settings.nopt)))
suc_res=np.zeros(len(iterparams[0])+1)
for n_p in np.arange(self.settings.nopt):
vect=iterparams[n_p]
print(vect)
#gp_notr.kernel.set_parameter_vector(vect)
try:
#logger.debug("vect"+','.join(list(vect.astype(str))))
result = op.minimize(neg_log_like, vect, args=(lc_trn[:,1], gp_notr), method="L-BFGS-B")#,jac=grad_neg_log_like)## jac=grad_nll,")
#logger.debug(','.join(list(gp_notr.get_parameter_vector().astype(str))))
if result.success:
#print("success,",result.fun)
suc_res=np.vstack((suc_res,np.hstack((result.x,result.fun))))
else:
fails+=1
#logger.debug(result.success+" - "+str(result.fun))
except:
#print("fail,",vect)
fails+=1
print(suc_res) if self.settings.verbose else logger.info(self.objname+" - succesful GP optimization with vector: "+','.join(list(suc_res.astype(str))))
print(str(fails)+" failed attempts out of "+str(self.settings.nopt)) if self.settings.verbose else logger.info(self.objname+str(fails)+" failed attempts out of "+str(self.settings.nopt))
if len(np.shape(suc_res))==1:
logger.warning("No successful GP minimizations")
raise ValueError("No successful GP minimizations")
else:
suc_res=suc_res[1:,:]
bestres=suc_res[np.argmin(suc_res[:,-1])]
gp_notr.set_parameter_vector(bestres[:-1])
self.optimised_gp=gp_notr
wn_factor = bestres[-3]-np.log(self.wn)
self.optgp={itrm:gp_notr.get_parameter(itrm) for itrm in gp_notr.get_parameter_names()}
# Update the kernel and print the final log-likelihood.
for itrm in gp_notr.kernel.get_parameter_names()[:-1]:
self.kern.set_parameter(itrm,gp_notr.kernel.get_parameter(itrm))
if self.settings.kernel=='quasi':
self.kern.freeze_parameter('terms[0]:log_factor') # re-freezing log factor
else:
self.kern.freeze_parameter('terms[1]:log_sigma') # and re-freezing white noise
#Adding
self.fitdict.update({'kernel:'+nm:np.random.normal(gp_notr.get_parameter('kernel:'+nm),1.5,self.settings.nwalkers) for nm in self.kern.get_parameter_names()})
print("white noise changed by a factor of "+str(np.exp(wn_factor))[:4]) if self.settings.verbose else logger.info(self.objname+"white noise changed by a factor of "+str(np.exp(wn_factor))[:4])
print("GP improved from ",init_res.fun," to ",bestres[-1]) if self.settings.verbose else logger.info(self.objname+"GP improved from "+init_res.fun+" to ",bestres[-1])
'''return bestres[:-2] #mean_shift... is this indicative of the whole lightcurve or just this half of it?'''
def AddMonotransit(self, tcen, tdur, depth, b=0.41,replace=True,name='mono1'):
'''
#Add's monotransit signal to a star
Requires:
* tcen (time of central transit, in the same units as the lightcurve)
* tdur (duration of transit)
* depth (depth of transit - in flux, not percent)
* b (optional, impact parameter, defaults to most likely value; 0.41)
* replace (optional, defauls to True. If False, should create a second monotransit)
* name (optional. Defaults to mono1)
'''
if not hasattr(self,'steffs'):
self.PDFs()
#Adding monotransit classes to the star class... Up to four possible.
if not hasattr(self,name) or replace:
#self.LD1s, self.LD2s, self.sdenss,self.Lcurve.lc,
setattr(self,name, Monotransit(tcen, tdur, depth, self.settings, name=str(self.objname)+'.1'))
if not hasattr(self,'sdenss'):
self.addDens()
getattr(self,name).calcmaxvel(self.Lcurve.lc,self.sdenss)
getattr(self,name).Optimize_mono(self.Lcurve.flatten(),self.LDprior.copy())
getattr(self,name).SaveInput(self.pdflist())
self.meanmodels+=[getattr(self,name)]
'''
while a<=5 and len(self.meanmodels)==initlenmonos:
if not hasattr(self,'mono'+str(a)) or replace:
setattr(self,'mono'+str(a)) = Monotransit(tcen, tdur, depth, self.settings, self.LD1s, self.LD2s, self.denss,self.lc, name=self.objname+'.'+str(a), b=b)
exec("self.mono"+str(a)+".Optimize_mono(Lcurve.flaten())")
exec("self.mono"+str(a)+".calcmaxvel(self.Lcurve.lc,self.sdenss)")
exec("self.meanmodels+=[self.mono"+str(a)+"]")
a+=1
'''
def AddNormalPlanet(self, tcen, tdur, depth, Period, b=0.41,replace=False):
'''
# This function should allow short-period planet signals (ie, non-monotransits) to be added to the model
'''
if not hasattr(self,'steffs'):
self.PDFs()
#Adding transiting planet classes to the star class using dfm's "transit"... Up to four possible.
if not hasattr(self,'norm1') or replace:
self.norm1 = Multtransit(tcen, tdur, depth, self.settings, name=self.objname+'.5', b=b)
self.meanmodels+=[self.norm1]
'''
while a<=5 and len(self.meanmodels)==initlenmonos:
if not hasattr(self,'mono'+str(a)) or replace:
setattr(self,'mono'+str(a)) = Monotransit(tcen, tdur, depth, self.settings, self.LD1s, self.LD2s, self.denss,self.lc, name=self.objname+'.'+str(a), b=b)
exec("self.mono"+str(a)+".Optimize_mono(Lcurve.flaten())")
exec("self.mono"+str(a)+".calcmaxvel(self.Lcurve.lc,self.sdenss)")
exec("self.meanmodels+=[self.mono"+str(a)+"]")
a+=1
'''
def initLD(self):
if not hasattr(self,'LD1s'):
self.EstLimbDark()
#Getting LD parameters for transit modelling:
self.LDprior={'LD1':[0,1.0,'gaussian',np.median(self.LD1s),np.std(self.LD1s)],
'LD2':[0,1.0,'gaussian',np.median(self.LD2s),np.std(self.LD2s)]}
def BuildMeanModel(self):
if not hasattr(self,'LD1s'):
self.EstLimbDark()
#for model in self.meanmodels: #<<<TBD
self.meanmodel_comb=MonotransitModel(tcen=self.mono1.tcen,
b=self.mono1.b,
vel=self.mono1.vel,
RpRs=self.mono1.RpRs,
LD1=np.median(self.LD1s),
LD2=np.median(self.LD2s))
def BuildMeanPriors(self):
#Building mean model priors
if not hasattr(self, 'LDprior'):
self.initLD()
if not hasattr(self,'meanmodel_comb'):
self.BuildMeanModel()
self.meanmodel_priors=self.mono1.priors.copy()
self.meanmodel_priors.update({'mean:'+ldp:self.LDprior[ldp] for ldp in self.LDprior})
def BuildAllPriors(self,keylist=None):
#Building priors from both GP and mean model and ordering by
if not hasattr(self, 'meanmodel_priors'):
self.BuildMeanPriors()
self.priors=self.meanmodel_priors.copy()#{key:self.meanmodel_priors[key] for key in self.meanmodel_priors.keys()}
if self.settings.GP:
self.priors.update({'kernel:'+self.kern.get_parameter_names()[keyn]:[self.kern.get_parameter_bounds()[keyn][0],
self.kern.get_parameter_bounds()[keyn][1]]
for keyn in range(len(self.kern.get_parameter_names()))
})
if 'kernel:terms[0]:log_amp' in self.kern.get_parameter_names():
self.priors['kernel:terms[0]:log_amp']=self.priors['kernel:terms[0]:log_amp']+['evans',0.25*len(self.Lcurve.lc[:,0])]
if 'kernel:terms[0]:log_a' in self.kern.get_parameter_names():
self.priors['kernel:terms[0]:log_a']=self.priors['kernel:terms[0]:log_a']+['evans',0.25*len(self.Lcurve.lc[:,0])]
if keylist is not None:
#Sorting to match parameter vector:
newprior={key:self.priors[key] for key in keylist}
#print(str(len(keylist))+" keys in vector leading to "+str(len(newprior))+" new keys in priors, from "+str(len(self.priors))+" initially") if self.settings.verbose else 0
self.priors=newprior
print(self.priors) if self.settings.verbose else logger.info(self.objname+' - Priors set as '+' , '.join([key+' - '+str(self.priors[key]) for key in self.priors.keys()]))
def RunMCMC(self):
self.BuildMeanPriors()
self.BuildMeanModel()
if self.settings.GP:
self.gp=celerite.GP(kernel=self.kern,mean=self.meanmodel_comb,fit_mean=True)
self.BuildAllPriors(self.gp.get_parameter_names())
else:
self.BuildAllPriors(list(self.fitdict.keys()))
#Returning monotransit model from information.
chx=np.random.choice(self.settings.npdf,self.settings.nwalkers,replace=False)
self.fitdict.update({'mean:'+nm:getattr(self.mono1,nm+'s')[chx] for nm in ['tcen','b','vel','RpRs']})
self.fitdict.update({'mean:'+nm:getattr(self,nm+'s')[chx] for nm in ['LD1','LD2']})
#Removing medians:
for row in self.fitdict:
self.fitdict[row][np.isnan(self.fitdict[row])]=np.nanmedian(np.isnan(self.fitdict[row]))
if self.settings.GP:
dists=[self.fitdict[cname] for cname in self.gp.get_parameter_names()]
else:
dists=[self.fitdict[cname] for cname in list(self.fitdict.keys())]
mask=abs(self.Lcurve.lc[:,0]-self.meanmodel_comb.get_parameter_dict()['tcen']<
(self.settings.ndurswindow*CalcTdur(self.meanmodel_comb.get_parameter_dict()['vel'],
self.meanmodel_comb.get_parameter_dict()['b'],
self.meanmodel_comb.get_parameter_dict()['RpRs']
)
)
)
self.init_mcmc_params=np.column_stack(dists)
# Cutting region around transit:
#Plotting:
if self.settings.GP:
PlotModel(self.Lcurve.lc[mask,:], self.gp, np.median(self.init_mcmc_params,axis=0), fname=self.settings.outfilesloc+self.objname+'_initfit.png',GP=True)
else:
PlotModel(self.Lcurve.lc[mask,:], self.meanmodel_comb, np.median(self.init_mcmc_params,axis=0), fname=self.settings.outfilesloc+self.objname+'_initfit.png',GP=False)
#dists=[np.random.normal(self.gp.get_parameter(nm),abs(self.gp.get_parameter(nm))**0.25,len(chx)) for nm in ['kernel:terms[0]:log_amp', 'kernel:terms[0]:log_timescale', 'kernel:terms[0]:log_period']]+\
# [self.tcens[chx],self.bs[chx],self.vels[~np.isnan(self.vels)][chx],self.RpRss[chx],self.LD1s[chx],self.LD2s[chx]]
#'kernel:terms[0]:log_factor', 'kernel:terms[1]:log_sigma' <- frozen and not used
#print(len(pos[0,:]))
#[np.array(list(initparams.values())) *(1+ 1.5e-4*np.random.normal()) for i in range(nwalkers)]
print("EMCEE HAPPENING. INIT DISTS:") if self.settings.verbose else logger.info(self.objname+" - EMCEE HAPPENING. INIT DISTS:")
print(self.init_mcmc_params[0,:]) if self.settings.verbose else logger.info(self.objname+' , '.join(list(self.init_mcmc_params[0,:].astype(str))))
if self.settings.GP:
print(self.gp.get_parameter_names()) if self.settings.verbose else logger.info(self.objname+' , '.join(list(self.gp.get_parameter_names())))
print(self.priors.keys()) if self.settings.verbose else logger.info(self.objname+' , '.join(list(self.priors.keys())))
#print(' , '.join( [str(list(self.priors.keys())[nk]) [-8:]+' - '+str(abs(self.priors[list(self.priors.keys())[nk]]-self.init_mcmc_params[nk]))[:5] for nk in range(len(self.priors.keys()))]) )
prilist=' \n '.join([str(list(self.priors.keys())[nk])+' - '+str(self.priors[list(self.priors.keys())[nk]][0])+" > "+str(np.median(self.init_mcmc_params[nk]))+\
" < "+str(self.priors[list(self.priors.keys())[nk]][1]) for nk in range(len(self.priors.keys()))]\
)
print(prilist) if self.settings.verbose else logger.info(self.objname+prilist)
sampler = emcee.EnsembleSampler(self.settings.nwalkers, len(dists), MonoLogProb, args=(self.Lcurve.lc[mask,:],self.priors,self.gp), threads=self.settings.nthreads)
else:
print(list(self.fitdict.keys())) if self.settings.verbose else logger.info(self.objname+' , '.join(list(self.fitdict.keys())))
print(self.priors.keys()) if self.settings.verbose else logger.info(self.objname+' , '.join(list(self.priors.keys())))
prilist=' \n '.join([str(list(self.priors.keys())[nk])+' - '+str(self.priors[list(self.priors.keys())[nk]][0])+" > "+str(np.median(self.init_mcmc_params[nk]))+\
" < "+str(self.priors[list(self.priors.keys())[nk]][1]) for nk in range(len(self.priors.keys()))]\
)
sampler = emcee.EnsembleSampler(self.settings.nwalkers, len(dists), MonoOnlyLogProb, args=(self.Lcurve.lc[mask,:],self.priors,self.meanmodel_comb), threads=self.settings.nthreads)
sampler.run_mcmc(self.init_mcmc_params, 1, rstate0=np.random.get_state())
sampler.run_mcmc(self.init_mcmc_params, self.settings.nsteps, rstate0=np.random.get_state())
#Trimming samples:
ncut=np.min([int(self.settings.nsteps*0.25),3000])
self.alllnprobs=sampler.lnprobability#[:,ncut:]#.reshape(-1)
prcnt=np.percentile(self.alllnprobs[:,ncut:],[50,95],axis=1)
#"Failed" walkers are where the 97th percentile is below the median of the rest
good_wlkrs=(prcnt[1]>np.median(prcnt[0]))
self.allsamples=sampler.chain
if self.settings.GP:
self.sampleheaders=list(self.gp.get_parameter_names())+['logprob']
else:
self.sampleheaders=list(self.fitdict.keys())+['logprob']
self.samples = self.allsamples[good_wlkrs, ncut:, :].reshape((-1, len(dists)))
self.samples = np.column_stack((self.samples,self.alllnprobs[good_wlkrs,ncut:].reshape(-1)))
#Making impact parameter always positive:
#self.samples[:,1]=abs(self.amples[:,1])
#self.SaveMCMC()
def SaveMCMC(self, samples=None, overwrite=False,suffix=''):
if path.exists(self.settings.outfilesloc+self.objname+'_MCMCsamples'+suffix) and not overwrite:
raise ValueError("Cannot save as file exists. Set, for example, overwrite=True, or suffix='_new'")
if not samples:
samples=self.samples
np.save(self.settings.outfilesloc+self.objname+'_MCMCsamples'+suffix,samples)
def SaveAll(self,overwrite=False,suffix=''):
if path.exists(self.settings.outfilesloc+self.objname+'_obj'+suffix+'.pickle') and not overwrite:
raise ValueError("Cannot save as file exists. Set, for example, overwrite=True, or suffix='_new'")
#Saves object
import pickle
with open(self.settings.outfilesloc+self.objname+'_obj'+suffix+'.pickle','wb') as picklefile:
pickle.dump(self, picklefile)
def MonoFinalPars(self,model=None):
if model is None and hasattr(self,'mono1'):
model=self.mono1
#Taking random Nsamples from samples to put through calculations
#Need to form assymetric gaussians of Star Dat parameters if not equal
#Rstardist2=np.hstack((np.sort(Rstardist[:, 0])[0:int(nsamp/2)], np.sort(Rstardist[:, 1])[int(nsamp/2):] ))
modelmeanvals=[col.find('mean:')!=-1 for col in self.sampleheaders]
model.gen_PDFs({self.sampleheaders[nmmv].split(":")[-1]+'s':self.samples[:,nmmv] for nmmv in range(len(self.sampleheaders)) if modelmeanvals[nmmv]})
rn=np.random.choice(len(self.samples[:,0]),self.settings.npdf,replace=False)
#for model in meanmodels:
setattr(model,'Rps',(self.samples[rn,self.sampleheaders.index('mean:RpRs')]*695500000*self.srads)/6.371e6)#inearths
setattr(model,'Prob_pl',len(model.Rps[model.Rps<(1.5*11.2)])/len(model.Rps))
aest,Pest=VelToOrbit(self.samples[rn,self.sampleheaders.index('mean:vel')], self.srads, self.smasss, self.sdenss)#Rs, Ms, dens
setattr(model,'smas',aest)
setattr(model,'Ps',Pest)
setattr(model,'Mps',PlanetRtoM(model.Rps))
setattr(model,'Krvs',((2.*np.pi*6.67e-11)/(model.Ps*86400))**(1./3.)*(model.Mps*5.96e24/((1.96e30*self.smasss)**(2./3.))))
#sigs=np.array([2.2750131948178987, , 97.7249868051821])
sigs=[15.865525393145707, 50.0, 84.13447460685429]
for val in ['Rps','smas','Ps','Mps','Krvs']:
percnts=np.percentile(np.array(getattr(model,val)), sigs)
setattr(model,val[:-1],percnts[1])
setattr(model,val[:-1]+'uerr',(percnts[2]-percnts[1]))
setattr(model,val[:-1]+'derr',(percnts[1]-percnts[0]))
def PlotMCMC(self,suffix='',usecols=None):
import corner
print(self.objname,"Plotting MCMC corner") if self.settings.verbose else logger.info(self.objname+" - Plotting MCMC corner")
if not self.settings.GP:
newnames={'mean:tcen':r'$t_{cen}$',
'mean:b':r'$b$',
'mean:vel':r'$v/R_s$',
'mean:RpRs':r'$R_p/R_s$',
'mean:LD1':r'LD$_1$',
'mean:LD2':r'LD$_2$'}
model2plot=self.meanmodel_comb
elif self.settings.kernel=='quasi':
newnames={'kernel:terms[0]:log_amp':r'$\log{a}$',
'kernel:terms[0]:log_timescale':r'$\log{\tau}$',
'kernel:terms[0]:log_period':r'$\log{P}$',
'mean:tcen':r'$t_{cen}$',
'mean:b':r'$b$',
'mean:vel':r'$v/R_s$',
'mean:RpRs':r'$R_p/R_s$',
'mean:LD1':r'LD$_1$',
'mean:LD2':r'LD$_2$'}
model2plot=self.gp
elif self.settings.kernel=='Real':
newnames={'kernel:terms[0]:log_a':r'$\log{a}$',
'kernel:terms[0]:log_c':r'$\log{c}$',
'mean:tcen':r'$t_{cen}$',
'mean:b':r'$b$',
'mean:vel':r'$v/R_s$',
'mean:RpRs':r'$R_p/R_s$',
'mean:LD1':r'LD$_1$',
'mean:LD2':r'LD$_2$'}
model2plot=self.gp
if usecols is None and self.settings.GP:
#Plotting corner with all parameter names
usecols=self.gp.get_parameter_names()
elif usecols is None and not self.settings.GP:
usecols=list(self.fitdict.keys())
plt.figure(1)
Npars=len(self.samples[0])-1
tobeplotted=np.tile(True,len(usecols))#np.in1d(self.gp.get_parameter_names(),usecols)
#Clipping extreme values (top.bottom 0.1 percentiles)
toclip=np.array([(np.percentile(self.samples[:,t],99.9)>self.samples[:,t])+(self.samples[:,t]>np.percentile(self.samples[:,t],0.1)) for t in np.arange(0,Npars,1)[tobeplotted]]).all(axis=0)
clipsamples=self.samples[toclip,:-1]
#Earmarking the difference between GP and non
labs = [newnames[key] for key in usecols]
#This plots the corner:
fig = corner.corner(clipsamples[:,tobeplotted], labels=labs, quantiles=[0.16, 0.5, 0.84], plot_datapoints=False,range=np.tile(0.985,Npars))
#Making sure the lightcurve plot doesnt overstep the corner
ndim=np.sum(tobeplotted)
rows=int((ndim)/2)+1
cols=int((ndim)/2)-1
#Printing Kepler name on plot
plt.subplot(ndim,ndim,3).axis('off')
plt.title(str(self.objname), fontsize=22)
#This plots the full lc at the top:
ax = plt.subplot2grid((ndim,ndim), (0, 2), rowspan=1, colspan=ndim-2)
modelfits=PlotModel(self.Lcurve.lc, model2plot, np.nanmedian(clipsamples,axis=0),GP=self.settings.GP) #(lc, samples, scale=1.0, GP=GP)
cliplc=self.Lcurve.lc[abs(self.Lcurve.lc[:,0]-self.mono1.tcen)<2.0,:]
if self.settings.GP:
#This plots the full lc at the top:
ax_zoom=plt.subplot2grid((ndim,ndim), (1, ndim-cols), rowspan=1, colspan=cols)
modelfits=PlotModel(cliplc, model2plot, np.nanmedian(clipsamples,axis=0),GP=self.settings.GP,title=False) #(lc, samples, scale=1.0, GP=GP)
#If we do a Gaussian Process fit, plotting both the transit-subtractedGP model and the residuals
ax=plt.subplot2grid((ndim,ndim), (2, ndim-cols), rowspan=1, colspan=cols)
_=PlotModel(cliplc, model2plot, np.nanmedian(clipsamples,axis=0), prevmodels=modelfits, subGP=True,GP=self.settings.GP,title=False)
#plotting residuals beneath:
ax = plt.subplot2grid((ndim*2,ndim*2), (6, 2*(ndim-cols)), rowspan=1, colspan=2*cols)
_=PlotModel(cliplc, model2plot, np.nanmedian(clipsamples,axis=0), prevmodels=modelfits, residuals=True,GP=self.settings.GP,title=False)
#Adding text values to MCMC pdf
#Plotting text wrt to residuals plot...
xlims=ax_zoom.get_xlim()
x0=xlims[0]-(0.5*(xlims[1]-xlims[0])) #Left of box in x
xwid=0.5*(xlims[1]-xlims[0]) #Total width of box in x
ylims=ax_zoom.get_ylim()
y1=ylims[1]-0.08*(ylims[1]-ylims[0]) #Top of y box
yheight=-5*(ylims[1]-ylims[0])/(rows-2) #Total height of box in y
else:
#This plots the full lc at the top:
ax_zoom=plt.subplot2grid((ndim,ndim), (1, ndim-cols), rowspan=1, colspan=cols)
modelfits=PlotModel(cliplc, model2plot, np.nanmedian(clipsamples,axis=0),GP=self.settings.GP,title=False) #(lc, samples, scale=1.0, GP=GP)
#Not GP:
ax=plt.subplot2grid((ndim*2,ndim*2), (4, 2*(ndim-cols)), rowspan=1, colspan=2*(cols))
_=PlotModel(cliplc, model2plot, np.nanmedian(clipsamples,axis=0), prevmodels=modelfits, residuals=True,GP=self.settings.GP,title=False)
#ax = plt.subplot2grid((ndim,ndim), (rows, ndim-cols-1), rowspan=1, colspan=cols+1)
#Adding text values to MCMC pdf
#Plotting text wrt to residuals plot...
xlims=ax_zoom.get_xlim()
xwid=0.5*(xlims[1]-xlims[0]) #Total width of box in x
x0=xlims[0]+xwid#-(0.5*(xlims[1]-xlims[0])) #Left of box in x
ylims=ax_zoom.get_ylim()
yheight=-5*(ylims[1]-ylims[0])/(rows-2) #Total height of box in y
y1=ylims[0]-0.8*(ylims[1]-ylims[0]) #Top of y box
from matplotlib import rc;rc('text', usetex=True);plt.rc('text', usetex=True)
#matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]
matplotlib.rc('font', family='serif', serif='cm10')
matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage{lmodern}']
matplotlib.rcParams['text.latex.preamble'] = [r'\boldmath']#Needed for latex commands here:
#matplotlib.rcParams['text.latex.preamble']=[r'\usepackage{amsmath}']
ax_zoom.text(x0+0.025*xwid,y1,"EPIC"+str(self.objname),fontsize=20)
n_textpos=0
txt=["EPIC"+str(self.objname)]
sigs=[2.2750131948178987, 15.865525393145707, 50.0, 84.13447460685429, 97.7249868051821]
for lab in labs:
xloc=x0+0.005*xwid
yloc=y1+0.02*yheight+(0.05*yheight*(n_textpos+1))
if lab==r'$t_{cen}$':#Need larger float size for Tcen...
txt+=[r'\textbf{'+lab+":} "+('%s' % float('%.8g' % (np.median(self.samples[:,n_textpos]))))+" +"+('%s' % float('%.2g' % (np.percentile(self.samples[:,n_textpos],sigs[3])-np.median(self.samples[:,n_textpos]))))+" -"+\
('%s' % float('%.2g' % (np.median(self.samples[:,n_textpos])-np.percentile(self.samples[:,n_textpos],sigs[1]))))]
ax_zoom.text(xloc,yloc,txt[-1])
else:
txt+=[r'\textbf{'+lab+":} "+('%s' % float('%.3g' % (np.median(self.samples[:,n_textpos]))))+" +"+('%s' % float('%.2g' % (np.percentile(self.samples[:,n_textpos],sigs[3])-np.median(self.samples[:,n_textpos]))))+" -"+\
('%s' % float('%.2g' % (np.median(self.samples[:,n_textpos])-np.percentile(self.samples[:,n_textpos],sigs[1]))))]
ax_zoom.text(xloc,yloc,txt[-1])
n_textpos+=1
info={'Rps':r'$R_p (R_{\oplus})$','Ps':'Per (d)','smas':'A (au)','Mps':r'$M_p (M_{\oplus})$','Krvs':r'K$_{rv}$(ms$^{-1}$)','Prob_pl':r'ProbPl ($\%$)',\
'steffs':'Teff (K)','srads':r'Rs ($R_{\odot}$)','smasss':r'Ms ($M_{\odot}$)','sloggs':'logg','sdenss':r'$\rho_s (\rho_{\odot})$'}
pdfs=self.pdflist()
for ival in pdfs:
if ival[:2]!='LD':
xloc=x0+0.005*xwid
yloc=y1+0.02*yheight+(0.05*yheight*(n_textpos+1.2))
vals=np.percentile(pdfs[ival],sigs)
txt+=[(r"\textbf{%s:} " % info[ival])+('%s' % float('%.3g' % vals[2]))+" +"+\
('%s' % float('%.2g' % (vals[3]-vals[2])))+" -"+('%s' % float('%.2g' % (vals[2]-vals[1])))]
ax_zoom.text(xloc,yloc,txt[-1])
n_textpos+=1
self.MonoFinalPars()
for ival in ['Rps','smas','Ps','Mps','Krvs']:
xloc=x0+0.05*xwid
yloc=y1+0.02*yheight+(0.05*yheight*(n_textpos+1.2))
vals=np.percentile(getattr(self.mono1,ival),sigs)
txt+=[(r"\textbf{%s:} " % info[ival])+('%s' % float('%.3g' % vals[2]))+" +"+\
('%s' % float('%.2g' % (vals[3]-vals[2])))+" -"+('%s' % float('%.2g' % (vals[2]-vals[1])))]
ax_zoom.text(xloc,yloc,txt[-1])
n_textpos+=1
xloc=x0+0.05*xwid
yloc=y1+0.02*yheight+(0.05*yheight*(n_textpos+1.2))
txt+=[(r"\textbf{%s:} " % info['Prob_pl'])+('%s' % float('%.3g' % getattr(self.mono1,'Prob_pl')))]
ax_zoom.text(xloc,yloc,txt[-1])
with open(self.settings.outfilesloc+'latextable.tex','a') as latextable:
latextable.write(' & '.join(txt)+'\n')
#Saving as pdf. Will save up to 3 unique files.
fname='';n=0
while fname=='':
if os.path.exists(self.settings.outfilesloc+'Corner_'+str(self.objname)+'_'+str(int(n))+'_'+suffix+'.pdf'):
n+=1
else:
fname=self.settings.outfilesloc+'/Corner_'+self.objname+'_'+str(int(n))+'_'+suffix+'.pdf'
plt.savefig(fname.replace('.pdf','.pdf'),Transparent=True,dpi=300)
plt.savefig(fname.replace('pdf','png'),Transparent=True,dpi=300)
class Monotransit():
#Monotransit detection to analyse
def __init__(self, tcen, tdur, depth, settings, name, b=0.4, RpRs=None, vel=None,\
tcenuerr=None,tduruerr=None,depthuerr=None,buerr=None,RpRsuerr=None, veluerr=None,\
tcenderr=None,tdurderr=None,depthderr=None,bderr=None,RpRsderr=None,velderr=None):
self.settings=settings
self.mononame = str(name)
self.starname = name.split('.')[0]
self.pdfs = {}
self.update_pars(tcen, tdur, depth, b=b, RpRs=RpRs, vel=vel,
tcenuerr=tcenuerr,tduruerr=tduruerr,depthuerr=depthuerr,buerr=buerr, RpRsuerr=RpRsuerr,veluerr=veluerr,
tcenderr=tcenderr,tdurderr=tdurderr,depthderr=depthderr,bderr=bderr,RpRsderr=RpRsderr, velderr=velderr)
self.gen_PDFs()
'''
def addStarDat(self,pdflist):
self.LD1s=pdflist['LD1s']
self.LD2s=pdflist['LD2s']
self.srads=pdflist['srads']
self.sdenss=pdflist['sdenss']
self.smasss=pdflist['smasss']
self.steffs=pdflist['steffs']
self.pdfs.update({'LD1s':self.LD1s,'LD2s':self.LD2s,'srads':self.srads,'sdenss':self.sdenss,'smasss':self.smasss,'steffs':self.steffs})
'''
def update_pars(self, tcen=None, tdur=None, depth=None, b=0.4, RpRs=None, vel=None, tcenuerr=None,tduruerr=None,depthuerr=None,buerr=None,RpRsuerr=None, tcenderr=None,tdurderr=None,depthderr=None,bderr=None,RpRsderr=None,veluerr=None,velderr=None):
if tcen is not None:
self.tcen = float(tcen) # detected transit centre
self.tcenuerr = 0.05*tdur if type(tcenuerr)==type(None) else tcenuerr # estimated transit centre errors (default = 0.1*dur)
self.tcenderr = 0.05*tdur if type(tcenderr)==type(None) else tcenderr # estimated transit centre errors (default = 0.1*dur)
if tdur is not None:
self.tdur = float(tdur) # detected transit duration
self.tduruerr = 0.33*tdur if type(tcenuerr)==type(None) else tcenuerr # estimated transit duration errors (default = 0.2*dur)
self.tdurderr = 0.33*tdur if type(tcenuerr)==type(None) else tcenuerr # estimated transit duration errors (default = 0.2*dur)
if depth is not None:
self.depth = float(depth) # detected transit depth
self.depthuerr = 0.33*depth if type(tcenuerr)==type(None) else tcenuerr # estimated transit depth errors (default = 0.1*depth)
self.depthderr = 0.33*depth if type(tcenuerr)==type(None) else tcenuerr # estimated transit depth errors (default = 0.1*depth)
self.b = 0.5 if type(b)==type(None) else b # estimated impact parameter (default = 0.5)
self.buerr = 0.5 if type(buerr)==type(None) else buerr # estimated impact parameter errors (default = 0.5)
self.bderr = 0.5 if type(bderr)==type(None) else bderr # estimated impact parameter errors (default = 0.5)
self.RpRs = self.depth**0.5 if type(RpRs)==type(None) else RpRs # Ratio of planet to star radius
self.RpRsuerr = 0.5*self.RpRs if type(RpRsuerr)==type(None) else RpRsuerr # Ratio of planet to star radius errors (default = 25%)
self.RpRsderr = 0.5*self.RpRs if type(RpRsderr)==type(None) else RpRsderr # Ratio of planet to star radius errors (default = 25%)
#self.vel = CalcVel() # Velocity of planet relative to stellar radius
if vel is not None:
self.vel = vel # Velocity scaled to stellar radius
elif not hasattr(self,'vel'):
self.vel = None # Velocity scaled to stellar radius
def gen_PDFs(self,paramdict=None):
#Turns params into PDFs
if paramdict is None:
self.tcens=GetAssymDist(self.tcen,self.tcenuerr,self.tcenderr,nd=self.settings.npdf,returndist=True)
#self.depths=GetAssymDist(self.depth,self.depthuerr,self.depthderr,nd=self.settings.npdf,returndist=True)
self.bs=abs(GetAssymDist(self.b,self.buerr,self.bderr,nd=self.settings.npdf,returndist=True))
self.RpRss=GetAssymDist(self.RpRs,self.RpRsuerr,self.RpRsderr,nd=self.settings.npdf,returndist=True)
#Velocity tends to get "Nan"-y, so looping to avoid that:
nanvels=np.tile(True,self.settings.npdf)
v=np.zeros(self.settings.npdf)
while np.sum(nanvels)>self.settings.npdf*0.002:
v[nanvels]=CalcVel(np.random.normal(self.tdur,self.tdur*0.15,nanvels.sum()), self.bs[np.random.choice(self.settings.npdf,np.sum(nanvels))], self.RpRss[np.random.choice(self.settings.npdf,np.sum(nanvels))])
nanvels=(np.isnan(v))*(v<0.0)*(v>100.0)
self.vels=v
prcnts=np.diff(np.percentile(self.vels[~np.isnan(self.vels)],[15.865525393145707, 50.0, 84.13447460685429]))
self.veluerr=prcnts[1]
self.velderr=prcnts[0]
if self.vel is not None and ~np.isnan(self.vel):
#Velocity pre-defined. Distribution is not, however, so we'll use the scaled distribution of the "derived" velocity dist to give the vel errors
velrat=self.vel/np.nanmedian(self.vels)
self.vels*=velrat
self.veluerr*=velrat
self.velderr*=velrat
else:
self.vel=np.nanmedian(self.vels)
else:
#included dictionary of new "samples"
sigs=[15.865525393145707, 50.0, 84.13447460685429]
for colname in ['tcens','bs','vels','RpRss']:
setattr(self,colname,paramdict[colname])
percnts=np.percentile(np.array(getattr(self,colname)), sigs)
setattr(self,colname[:-1],percnts[1])
setattr(self,colname[:-1]+'uerr',percnts[2]-percnts[1])
setattr(self,colname[:-1]+'derr',percnts[1]-percnts[0])
self.pdfs.update({'tcens':self.tcens,'bs':self.bs,'RpRss':self.RpRss,'vels':self.vels})
#if StarPDFs is not None:
# self.pdflist.update(StarPDFs)
def loadmodel(self,LDprior):
self.model=MonotransitModel(tcen=self.tcen,
b=self.b,
vel=self.vel,
RpRs=self.RpRs,
LD1=LDprior['LD1'][3],
LD2=LDprior['LD2'][3])
def calcmaxvel(self,lc,sdenss):
#Estimate maximum velocity given lightcurve duration without transit.
self.calcminp(lc)
maxvels=np.array([((18226*rho)/self.minp)**(1/3.0) for rho in abs(sdenss)])
prcnts=np.percentile(maxvels,[15.865525393145707, 50.0, 84.13447460685429])
self.maxvelderr=prcnts[1]-prcnts[0]
self.maxvel=prcnts[1]
self.maxveluerr=prcnts[2]-prcnts[1]
def calcminp(self,lc):
#finding tdur-wide jumps in folded LC
dur_jumps=np.where(np.diff(abs(lc[:,0]-self.tcen))>self.tdur)[0]
if len(dur_jumps)==0:
#No tdur-wide jumps until end of lc - using the maximum difference to a point in the lc
self.minp=np.max(abs(lc[:,0]-self.tcen))+self.tdur*0.33
else:
#Taking the first Tdur-wide jump in the folded lightcurve where a transit could be hiding.
self.minp=abs(lc[:,0]-self.tcen)[dur_jumps[0]]+self.tdur*0.33
'''
def CalcOrbit(self,denss):
#Calculating orbital information
#VelToOrbit(Vel, Rs, Ms, ecc=0, omega=0):
SMA,P=Vel2Per(denss,self.vels)
self.SMAs=SMA
self.PS=P
def update(self, **kwargs):
#Modify detection parameters...
self.tcen = kwargs.pop('tcen', self.tcen) # detected transit centre
self.tdur = kwargs.pop('tdur', self.tdur) # detected transit duration
self.depth = kwargs.pop('dep', self.depth) # detected transit depth
self.b = kwargs.pop('b', self.b) # estimated impact parameter (default = 0.4)
self.RpRs = kwargs.pop('RpRs', self.RpRs) # Ratio of planet to star radius
self.vel = kwargs.pop('vel', self.vel) # Velocity of planet relative to stellar radius
def FitParams(self,star,info):
#Returns params array needed for fitting
if info.GP:
return np.array([self.tcen,self.b,self.vel,self.RpRs])
else:
return np.array([self.tcen,self.b,self.vel,self.RpRs])
def InitialiseGP(self,settings,star,Lcurve):
import george
self.gp, res, self.lnlikfit = TrainGP(Lcurve.lc,self.tcen,star.wn)
self.newmean,self.newwn,self.a,self.tau=res
def FitPriors(self,star,settings):
#Returns priros array needed for fitting
if settings.GP:
if not self.hasattr('tau'):
self.InitialiseGP()
return np.array([[self.tcen,self.tcen,self.tcen,self.tcen],
[-1.2,1.2,0,0],
[0.0,100.0,self.vmax,self.vmaxerr],
[0.0,0.3,0,0],
[0.0,1.0,star.LD1,np.average(star.LD1uerr,star.LD1derr)],
[0.0,1.0,star.LD2,np.average(star.LD2uerr,star.LD2derr)],
[np.log(star.wn)-1.5,np.log(star.wn)+1.5,np.log(star.wn),0.3],
[self.tau-10,self.tau+10,self.tau,np.sqrt(np.abs(self.tau))],
[self.a-10,self.a+10,self.a,np.sqrt(np.abs(self.a))]])
else:
return np.array([[self.tcen,self.tcen,self.tcen,self.tcen],
[-1.2,1.2,0,0],
[0.0,100.0,self.vmax,self.vmaxerr],
[0.0,0.3,0,0],
[0.0,1.0,star.LD1,np.average(star.LD1uerr,star.LD1derr)],
[0.0,1.0,star.LD2,np.average(star.LD2uerr,star.LD2derr)]]
'''
def Optimize_mono(self,flatlc,LDprior,nopt=20):
if not hasattr(self,'priors'):
self.monoPriors()
#Cutting to short area around transit:
flatlc=flatlc[abs(flatlc[:,0]-self.tcen)<5*self.tdur]
#Optimizing initial transit parameters
opt_monomodel=MonotransitModel(tcen=self.tcen,
b=self.b,
vel=self.vel,
RpRs=self.RpRs,
LD1=LDprior['LD1'][3],
LD2=LDprior['LD2'][3])
temp_priors=self.priors.copy()
temp_priors['mean:LD1'] = LDprior['LD1']
temp_priors['mean:LD2'] = LDprior['LD2']
print("monopriors:",temp_priors) if self.settings.verbose else logger.info(self.mononame+" - monopriors: "+' , '.join([key+' - '+str(temp_priors[key]) for key in temp_priors.keys()]))
init_neglogprob=MonoOnlyNegLogProb(opt_monomodel.get_parameter_vector(),flatlc,temp_priors,opt_monomodel)
print("nll init",init_neglogprob) if self.settings.verbose else logger.info(self.mononame+" - nll init: "+str(init_neglogprob))
suc_res=np.zeros(7)
LD1s=np.random.normal(LDprior['LD1'][3],LDprior['LD1'][4],self.settings.npdf)
LD2s=np.random.normal(LDprior['LD2'][3],LDprior['LD2'][4],self.settings.npdf)
#Running multiple optimizations using rough grid of important model paramsself.
for n_par in np.random.choice(self.settings.npdf,nopt,replace=False):
initpars=np.array([self.tcens[n_par],self.bs[n_par],self.vels[n_par],self.RpRss[n_par],LD1s[n_par],LD2s[n_par]])
result = opt.minimize(MonoOnlyNegLogProb, initpars, args=(flatlc, temp_priors, opt_monomodel), method="L-BFGS-B")
if result.success:
suc_res=np.vstack((suc_res,np.hstack((result.x,result.fun))))
if len(np.shape(suc_res))==1:
raise ValueError("No successful Monotransit minimizations")
else:
#Ordering successful optimizations by neglogprob...
suc_res=suc_res[1:,:]
#print("All_Results:",suc_res) if self.settings.verbose else logger.info(self.objname,"mono opt, All_Results:",suc_res)
suc_res=suc_res[~np.isnan(suc_res[:,-1]),:]
bestres=suc_res[np.argmin(suc_res[:,-1])]
self.bestres=bestres
print("Best_Result:",bestres) if self.settings.verbose else logger.info(self.mononame+" - mono opt, Best Results:"+' , '.join(list(bestres.astype(str))))
#tcen, tdur, depth, b=0.4, RpRs=None, vel=None
self.update_pars(bestres[0], CalcTdur(bestres[2], bestres[1], bestres[3]), bestres[3]**2, b=bestres[1], RpRs=bestres[3],vel=bestres[2])
print("initial fit nll: ",init_neglogprob," to new fit nll: ",bestres[-1]) if self.settings.verbose else logger.info(self.mononame+"initial fit nll: "+str(init_neglogprob)+" to new fit nll: "+' , '.join(list(bestres[-1].astype(str))))
#for nn,name in enumerate(['mean:tcen', 'mean:b', 'mean:vel', 'mean:RpRs', 'mean:LD1', 'mean:LD2']):
# self.gp.set_parameter(name,bestres[nn])
PlotBestMono(flatlc, opt_monomodel, bestres[:-1], fname=self.settings.outfilesloc+self.mononame+'_init_monoonly_fit.png')
def monoPriors(self,name='mean'):
self.priors={}
self.priors.update({name+':tcen':[self.tcen-self.tdur*0.3,self.tcen+self.tdur*0.3],
name+':b':[0.0,1.25],
name+':vel':[0,self.maxvel+5*self.maxveluerr,'normlim',self.maxvel,self.maxveluerr],
name+':RpRs':[0.02,0.25]
})
return self.priors
'''
def RunModel(self,lc,gp):
self.modelPriors()
#Returning monotransit model from information.
sampler = emcee.EnsembleSampler(self.settings.nwalkers, len(gp.get_parameter_vector()), MonoLogProb, args=(lc,self.priors,gp), threads=self.settings.nthreads)
chx=np.random.choice(np.sum(~np.isnan(self.vels)),self.settings.nwalkers,replace=False)
dists=[np.random.normal(gp.get_parameter(nm),abs(gp.get_parameter(nm))**0.25,len(chx)) for nm in ['kernel:terms[0]:log_amp', 'kernel:terms[0]:log_timescale', 'kernel:terms[0]:log_period']]+\
[self.tcens[chx],self.bs[chx],self.vels[~np.isnan(self.vels)][chx],self.RpRss[chx],self.LD1s[chx],self.LD2s[chx]]
#'kernel:terms[0]:log_factor', 'kernel:terms[1]:log_sigma' <- frozen and not used
col=['kernel:terms[0]:log_amp', 'kernel:terms[0]:log_timescale', 'kernel:terms[0]:log_period',\
'mean:tcen','mean:b','mean:vel','mean:RpRs','mean:LD1','mean:LD2']
pos=np.column_stack(dists)
self.init_mcmc_params=pos
#print(len(pos[0,:]))
#[np.array(list(initparams.values())) *(1+ 1.5e-4*np.random.normal()) for i in range(nwalkers)]
Nsteps = 30000
sampler.run_mcmc(pos, 1, rstate0=np.random.get_state())
sampler.run_mcmc(pos, self.settings.nsteps, rstate0=np.random.get_state())
self.samples = sampler.chain[:, 3000:, :].reshape((-1, ndim))
return self.samples
#.light_curve(np.arange(0,40,0.024),texp=0.024))
'''
def SaveInput(self,stellarpdfs):
np.save(self.settings.fitsloc+self.mononame+'_inputsamples',np.column_stack(([self.pdfs[ipdf] for ipdf in self.pdfs.keys()]+[stellarpdfs[ipdf] for ipdf in stellarpdfs.keys()])))
class Lightcurve():
# Lightcurve class - contains all lightcurve information
def __init__(self, file, epic, settings):
self.settings=settings
self.fileloc=file
self.lc,self.mag=OpenLC(self.fileloc)
try:
self.mag=k2_quickdat(epic)['k2_kepmag']
except:
self.mag=self.mag
self.lc=self.lc[~np.isnan(np.sum(self.lc,axis=1))]
self.fluxmed=np.nanmedian(self.lc[:,1])
self.lc[:,1:]/=self.fluxmed
self.lc=self.lc[AnomCutDiff(self.lc[:,1],self.settings.anomcut)]
self.range=self.lc[-1,0]-self.lc[self.lc[:,0]!=0.0,0][0]
self.cadence=np.nanmedian(np.diff(self.lc[:,0]))
self.lcmask=np.tile(True,len(self.lc[:,0]))
def BinLC(self, binsize,gap=0.4):
#Bins lightcurve to some time interval. Finds gaps in the lightcurve using the threshold "gap"
spl_ts=np.array_split(self.lc[:,0],np.where(np.diff(self.lc[:,0])>gap)[0]+1)
bins=np.hstack([np.arange(s[0],s[-1],binsize) for s in spl_ts])
digitized = np.digitize(self.lc[:,0], bins)
ws=(self.lc[:,2])**-2.0
ws=np.where(ws==0.0,np.median(ws[ws!=0.0]),ws)
bin_means = np.array([np.ma.average(self.lc[digitized==i,2],weights=ws[digitized==i]) for i in range(np.max(digitized))])
bin_stds = np.array([np.ma.average((self.lc[digitized==i,2]-bin_means[i])**2, weights=ws[digitized==i]) for i in range(np.max(digitized))])
whok=(~np.isnan(bin_means))&(bin_means!=0.0)
self.binlc=np.column_stack((bins,bin_means,bin_stds))[whok,:]
self.binsize=binsize
return self.binlc
'''
def keys(self):
return ['NPTS','SKY_TILE','RA_OBJ','DEC_OBJ','BMAG','VMAG','JMAG','KMAG','HMAG','PMRA','PMDEC','PMRAERR','PMDECERR','NFIELDS']
def keyvals(self,*args):
#Returns values for the given key list
arr=[]
for ke in args[0]:
exec('arr+=[self.%s]' % ke)
return arr
'''
def savelc(self):
np.save(self.settings.fitsloc+self.OBJNAME.replace(' ','')+'_bin.npy',self.get_binlc())
np.save(self.settings.fitsloc+self.OBJNAME.replace(' ','')+'.npy',self.get_lc())
def flatten(self,winsize=4.5,stepsize=0.125):
from . import k2flatten
return k2flatten.ReduceNoise(self.lc,winsize=winsize,stepsize=stepsize)
def calc_mask(self,meanmodels):
for model in meanmodels:
if hasattr(model,'P'):
self.lcmask[((abs(self.lc[:,0]-model.tcen)%model.P)<(self.cadence+model.tdur*0.5))+((abs(self.lc[:,0]-model.tcen)%model.P)>(model.P-(model.tdur*0.5+self.cadence)))]=False
else:
#Mono
self.lcmask[abs(self.lc[:,0]-model.tcen)<(self.cadence+model.tdur*0.5)]=False
class MonotransitModel(celerite.modeling.Model):
parameter_names = ("tcen", "b","vel","RpRs","LD1","LD2")
def get_value(self,t):
#Getting fine cadence (cad/100). Integrating later:
cad=np.median(np.diff(t))
oversamp=10#Oversampling
finetime=np.hstack(([t+overts for overts in cad*np.arange(0,1.0,1/oversamp)]))
finetime=np.sort(finetime)
z = np.sqrt(self.b**2+(self.vel*(finetime - self.tcen))**2)
#Removed the flux component below. Can be done by GP
model = occultquad(z, self.RpRs, np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)
'''
#TBD:
class MonotransitModel_x2(celerite.modeling.Model):
nmodels=2
parameter_names = tuple([item for sublist in [["tcen"+str(n), "b"+str(n),"vel"+str(n),"RpRs"+str(n)] for n in range(1,nmodels+1)]+[["LD1","LD2"]] for item in sublist ])
def get_value(self,t):
cad=np.median(np.diff(t))
oversamp=10#Oversampling
finetime=np.hstack(([t+overts for overts in cad*np.arange(0,1.0,1/oversamp)]))
finetime=np.sort(finetime)
model=np.zeros((len(finetime)))
for nmod in range(nmodels):
z = np.sqrt(getattr(self,'b'+str(nmod))**2+(getattr(self,'vel'+str(nmod))*(finetime - getattr(self,'tcen'+str(nmod))))**2)
#Removed the flux component below. Can be done by GP
model *= occultquad(z, getattr(self,'RpRs'+str(nmod)), np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)
class MonotransitModel_x3(celerite.modeling.Model):
nmodels =3
parameter_names = tuple([item for sublist in [["tcen"+str(n), "b"+str(n),"vel"+str(n),"RpRs"+str(n)] for n in range(1,nmodels+1)]+[["LD1","LD2"]] for item in sublist ])
def get_value(self,t):
cad=np.median(np.diff(t))
oversamp=10#Oversampling
finetime=np.hstack(([t+overts for overts in cad*np.arange(0,1.0,1/oversamp)]))
finetime=np.sort(finetime)
model=np.zeros((len(finetime)))
for nmod in range(nmodels):
z = np.sqrt(getattr(self,'b'+str(nmod))**2+(getattr(self,'vel'+str(nmod))*(finetime - getattr(self,'tcen'+str(nmod))))**2)
#Removed the flux component below. Can be done by GP
model *= occultquad(z, getattr(self,'RpRs'+str(nmod)), np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)
import batman
class MonotransitModel_plus_pl(celerite.modeling.Model):
parameter_names = ("monotcen", "monob","monovel","monoRpRs","multitcen", "multib","multiP","multiRpRs","multia_Rs","LD1","LD2")
def get_value(self,t):
oversamp=10#Oversampling
params = batman.TransitParams()
params.t0 = self.multitcen #time of inferior conjunction
params.per = self.multiP #orbital period
params.rp = self.multiRpRs #planet radius (in units of stellar radii)
params.a = self.multia_Rs #semi-major axis (in units of stellar radii)
params.inc = np.acos(self.multib/self.multia_Rs) #orbital inclination (in degrees)
params.u = [self.LD1, self.LD2] #limb darkening coefficients
params.ecc = 0.;params.w = 90.;params.limb_dark = "quadratic"
multilc=batman.TransitModel(params,t,supersample_factor=oversamp).light_curve(params)
cad=np.median(np.diff(t))
finetime=np.hstack(([t+overts for overts in cad*np.arange(0,1.0,1/oversamp)]))
finetime=np.sort(finetime)
model=np.zeros((len(finetime)))
for nmod in range(nmodels):
z = np.sqrt(getattr(self,'b'+str(nmod))**2+(getattr(self,'vel'+str(nmod))*(finetime - getattr(self,'tcen'+str(nmod))))**2)
#Removed the flux component below. Can be done by GP
model *= occultquad(z, getattr(self,'RpRs'+str(nmod)), np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)-(1.0-multilc)
class MonotransitModel_plus_plx2(celerite.modeling.Model):
parameter_names = tuple(["monotcen", "monob","monovel","monoRpRs"]+
['multi'+item for sublist in [["tcen"+str(n), "b"+str(n),"P"+str(n),"RpRs"+str(n),"a_Rs"+str(n)] for n in range(1,3)]+
[["LD1","LD2"]] for item in sublist ])
def get_value(self,t):
cad=np.median(np.diff(t))
oversamp=10#Oversampling
p1 = batman.TransitParams()
p1.t0 = self.multitcen1 #time of inferior conjunction
p1.per = self.multiP1 #orbital period
p1.rp = self.multiRpRs1 #planet radius (in units of stellar radii)
p1.a = self.multia_Rs1 #semi-major axis (in units of stellar radii)
p1.inc = np.acos(self.multib1/self.multia_Rs1) #orbital inclination (in degrees)
p1.u = [self.LD1, self.LD2] #limb darkening coefficients
p1.ecc = 0.;p1.w = 90.;p1.limb_dark = "quadratic"
p2 = batman.TransitParams()
p2.t0 = self.multitcen2 #time of inferior conjunction
p2.per = self.multiP2 #orbital period
p2.rp = self.multiRpRs2 #planet radius (in units of stellar radii)
p2.a = self.multia_Rs2 #semi-major axis (in units of stellar radii)
p2.inc = np.acos(self.multib2/self.multia_Rs2) #orbital inclination (in degrees)
p2.u = [self.LD1, self.LD2] #limb darkening coefficients
p2.ecc = 0.;p2.w = 90.;p2.limb_dark = "quadratic"
multilc=batman.TransitModel(p1,t,supersample_factor=oversamp).light_curve(p1)-(1.0-batman.TransitModel(p1,t,supersample_factor=oversamp).light_curve(p1))
finetime=np.hstack(([t+overts for overts in cad*np.arange(0,1.0,1/oversamp)]))
finetime=np.sort(finetime)
model=np.zeros((len(finetime)))
for nmod in range(1,3):
z = np.sqrt(getattr(self,'b'+str(nmod))**2+(getattr(self,'vel'+str(nmod))*(finetime - getattr(self,'tcen'+str(nmod))))**2)
#Removed the flux component below. Can be done by GP
model *= occultquad(z, getattr(self,'RpRs'+str(nmod)), np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)-(1.0-multilc)
class MonotransitModelx3_plus_plx2(celerite.modeling.Model):
parameter_names = tuple(['mono'+item for sublist in [["tcen"+str(n), "b"+str(n),"vel"+str(n),"RpRs"+str(n)] for n in range(1,4)]]+\
['multi'+item for sublist in [["tcen"+str(n), "b"+str(n),"P"+str(n),"RpRs"+str(n),"a_Rs"+str(n)] for n in range(4,6)]]+\
["LD1","LD2"]])
def get_value(self,t):
cad=np.median(np.diff(t))
oversamp=10#Oversampling
multilc=np.zeros_like(t)
for nmodel in range(1,2):
params = batman.TransitParams()
params.t0 = getattr(self,'multitcen'+str(nmodel)) #time of inferior conjunction
params.per = getattr(self,'multiP'+str(nmodel)) #orbital period
params.rp = getattr(self,'multiRpRs'+str(nmodel)) #planet radius (in units of stellar radii)
params.a = getattr(self,'multia_Rs+str(nmodel)) #semi-major axis (in units of stellar radii)
params.inc = np.acos(getattr(self,'multib'+str(nmodel))/params.a) #orbital inclination (in degrees)
params.u = [self.LD1, self.LD2] #limb darkening coefficients
params.ecc = 0.;params.w = 90.;params.limb_dark = "quadratic"
multilc+=(1-batman.TransitModel(params,t,supersample_factor=oversamp).light_curve(params))
finetime=np.hstack(([t+overts for overts in cad*np.arange(0,1.0,1/oversamp)]))
finetime=np.sort(finetime)
model=np.zeros((len(finetime)))
for nmod in range(1,4):
z = np.sqrt(getattr(self,'b'+str(nmod))**2+(getattr(self,'vel'+str(nmod))*(finetime - getattr(self,'tcen'+str(nmod))))**2)
#Removed the flux component below. Can be done by GP
model *= occultquad(z, getattr(self,'RpRs'+str(nmod)), np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)+multilc
'''
def k2_quickdat(kic):
kicdat=pd.DataFrame.from_csv("https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?table=k2targets&where=epic_number=%27"+str(int(kic))+"%27")
if len(kicdat.shape)>1:
kicdat=kicdat.iloc[0]
return kicdat
'''
def MonoLnPriorDict(params,priors):
lp=0
for key in priors.keys():
#print(params[n],key,priors[key])
if params[key]<priors[key][0] or params[key]>priors[key][1]:
#hidesously low number that still has gradient towards "mean" of the uniform priors.
lp-=1e15 * (params[key]-(0.5*(priors[key][0]+priors[key][1])))**2
#print(key," over prior limit")
if len(priors[key])>2:
if priors[key][2]=='gaussian':
lp+=stats.norm(priors[key][3],priors[key][4]).pdf(params[key])
elif priors[key][2]=='normlim':
#Special velocity prior from min period & density:
lp+=((1.0-stats.norm.cdf(params[key],priors[key][3],priors[key][4]))*params[key])**2
return lp
'''
def MonoLnPrior(params,priors):
lp=0
for n,key in enumerate(priors.keys()):
#print(params[n],key,priors[key])
if params[n]<priors[key][0] or params[n]>priors[key][1]:
#hideously low number that still has gradient towards "mean" of the uniform priors. Scaled by prior width
lp-=1e20 * (((params[n]-0.5*(priors[key][0]+priors[key][1])))/(priors[key][1]-priors[key][0]))**2
#print(key," over prior limit")
if len(priors[key])>2:
if priors[key][2]=='gaussian':
lp+=stats.norm(priors[key][3],priors[key][4]).pdf(params[n])
elif priors[key][2]=='normlim':
#Special velocity prior from min period & density:
lp+=((1.0-stats.norm.cdf(params[n],priors[key][3],priors[key][4]))*params[n])**2
elif priors[key][2]=='evans':
#Evans 2015 limit on amplitude - same as p(Ai) = Gam(1, 100) (apparently, although I cant see it.)
#Basically prior is ln
lp-=priors[key][3]*np.exp(params[n])#
return lp
def MonoLogProb(params,lc,priors,gp):
gp.set_parameter_vector(params)
gp.compute(lc[:,0],lc[:,2])
ll = gp.log_likelihood(lc[:,1])
lp = MonoLnPrior(params,priors)
return (ll+lp)
def MonoNegLogProb(params,lc,priors,gp):
return -1*MonoLogProb(params,lc,priors,gp)
def MonoOnlyLogProb(params,lc,priors,monomodel):
monomodel.set_parameter_vector(params)
ll = np.sum(-2*lc[:,2]**-2*(lc[:,1]-monomodel.get_value(lc[:,0]))**2)#-(0.5*len(lc[:,0]))*np.log(2*np.pi*lc[:,2]**2) #Constant not neceaary for gradient descent
lp = MonoLnPrior(params,priors)
return (ll+lp)
def MonoOnlyNegLogProb(params,lc,priors,monomodel):
return -1*MonoOnlyLogProb(params,lc,priors,monomodel)
class RotationTerm(celerite.terms.Term):
parameter_names = ("log_amp", "log_timescale", "log_period", "log_factor")
def get_real_coefficients(self, params):
log_amp, log_timescale, log_period, log_factor = params
if type(log_factor)==np2.numpy_boxes.ArrayBox:
log_factor=log_factor._value#flatten#.astype(float)
#log_factor=log_factor.astype(float)
#print(log_factor)
# f = log_factor.__rpow__(np.exp(1))
# print(f)
# return (log_amp.__rpow__(np.exp(1)).__mul__(f.__add__(1.0)).__div__(f.__add__(2.0)),log_timescale.__mul__(-1).__rpow__(np.exp(1)))
#else:
f = np2.exp(log_factor)
return (np2.exp(log_amp) * (1.0 + f) / (2.0 + f),np2.exp(-log_timescale))
def get_complex_coefficients(self, params):
log_amp, log_timescale, log_period, log_factor = params
f = np2.exp(log_factor)
return (
np2.exp(log_amp) / (2.0 + f),
0.0,
np2.exp(-log_timescale),
2*np.pi*np2.exp(-log_period),
)
def neg_log_like(params, y, gp):
gp.set_parameter_vector(params)
return -gp.log_likelihood(y)
def grad_neg_log_like(params, y, gp):
gp.set_parameter_vector(np.array(params))
return -gp.grad_log_likelihood(y)[1]
'''
def grad_nll(p,gp,y,prior=[]):
#Gradient of the objective function for TrainGP
gp.set_parameter_vector(p)
return -gp.grad_log_likelihood(y, quiet=True)
def nll_gp(p,gp,y,prior=[]):
#inverted LnLikelihood function for GP training
gp.set_parameter_vector(p)
if prior!=[]:
prob=MonoLogProb(p,y,prior,gp)
return -prob if np.isfinite(prob) else 1e25
else:
ll = gp.log_likelihood(y, quiet=True)
return -ll if np.isfinite(ll) else 1e25'''
def VelToOrbit(vel, Rs, Ms, dens=None, ecc=0, omega=0,timebin=86400.0):
'''Takes in velocity (in units of stellar radius), Stellar radius estimate and (later) eccentricity & angle of periastron.
Returns Semi major axis (AU) and period (days)'''
if dens is None:
dens=Ms/Rs**3
Per=18226*dens/(vel**3)
# 13.7375 = G*M_sol*au^-1*R_sun^-2*(secs/d)^2 = ((1.3271244e20)/(695700000/86400)**2)/1.49e11
SMA= 13.7375*(Ms*(Rs/vel)**2)
return SMA, Per
def getKeplerLDs(Ts,logg=4.43812,FeH=0.0,how='2'):
#Get Kepler Limb darkening coefficients.
from scipy.interpolate import CloughTocher2DInterpolator as ct2d
#print(label)
types={'1':[3],'2':[4, 5],'3':[6, 7, 8],'4':[9, 10, 11, 12]}
if how in types:
checkint = types[how]
#print(checkint)
else:
print("no key...")
#arr = np.genfromtxt("KeplerLDlaws.txt",skip_header=2)
try:
arr = np.genfromtxt("KeplerLDlaws.txt",skip_header=2)
except:
arr = np.genfromtxt("KeplerLDlaws.txt",skip_header=2)
FeHarr=np.unique(arr[:, 2])
#Just using a single value of FeH
if not (type(FeH)==float) and not (type(FeH)==int):
FeH=np.nanmedian(FeH)
FeH=FeHarr[find_nearest(FeHarr,FeH)]
feh_ix=arr[:,2]==FeH
feh_ix=arr[:,2]==FeH
Tlen=1 if type(Ts)==float or type(Ts)==int else len(Ts)
outarr=np.zeros((Tlen,len(checkint)))
for n,i in enumerate(checkint):
u_interp=ct2d(np.column_stack((arr[feh_ix,0],arr[feh_ix,1])),arr[feh_ix,i])
if (type(Ts)==float)+(type(Ts)==int) and ((Ts<50000.)*(Ts>=2000)):
outarr[0,n]=u_interp(Ts,logg)
elif ((Ts<50000.)*(Ts>=2000)).all():
if type(logg)==float:
outarr[:,n]=np.array([u_interp(T,logg) for T in Ts])
else:
outarr[:,n]=np.array([u_interp(Ts[t],logg[t]) for t in range(len(Ts))])
else:
print('Temperature outside limits')
outarr=None
break
return outarr
def nonan(lc):
return np.logical_not(np.isnan(np.sum(lc,axis=1)))
def AnomCutDiff(flux,thresh=4.2):
#Uses differences between points to establish anomalies.
#Only removes single points with differences to both neighbouring points greater than threshold above median difference (ie ~rms)
#Fast: 0.05s for 1 million-point array.
#Must be nan-cut first
diffarr=np.vstack((np.diff(flux[1:]),np.diff(flux[:-1])))
diffarr/=np.median(abs(diffarr[0,:]))
anoms=np.hstack((True,((diffarr[0,:]*diffarr[1,:])>0)+(abs(diffarr[0,:])<thresh)+(abs(diffarr[1,:])<thresh),True))
return anoms
def CalcTdur(vel, b, p):
'''Caculates a velocity (in v/Rs) from the input transit duration Tdur, impact parameter b and planet-to-star ratio p'''
# In Rs per day
return (2*(1+p)*np.sqrt(1-(b/(1+p))**2))/vel
def CalcVel(Tdur, b, p):
'''Caculates a velocity (in v/Rs) from the input transit duration Tdur, impact parameter b and planet-to-star ratio p'''
# In Rs per day
return (2*(1+p)*np.sqrt(1-(b/(1+p))**2))/Tdur
def PlotBestMono(lc, monomodel, vector, fname=None):
cad=np.median(np.diff(lc[:,0]))
t=np.arange(lc[0,0],lc[-1,0]+0.01,cad)
monomodel.set_parameter_vector(vector)
ypred=monomodel.get_value(t)
plt.errorbar(lc[:, 0], lc[:,1], yerr=lc[:, 2], fmt='.',color='#999999')
plt.plot(lc[:, 0], lc[:,1], '.',color='#333399')
plt.plot(t,ypred,'--',color='#003333',linewidth=2.0,label='Median transit model fit')
if fname is not None:
plt.savefig(fname)
def PlotModel(lc, model, vector, prevmodels=[], plot=True, residuals=False, scale=1, nx=10000, GP=False, subGP=False, monomodel=0, verbose=True,fname=None,title=True):
# - lc : lightcurve
# - model : celerite-style model (eg gp) to apply the vector to
# - vector : best-fit parameters to use
cad=np.median(np.diff(lc[:,0]))
t=np.arange(lc[0,0],lc[-1,0]+cad*0.5,cad)
if len(prevmodels)==0:
model.set_parameter_vector(vector)
if GP:
model.compute(lc[:,0],lc[:,2])
ypreds,varpreds=model.predict(lc[:,1], t)
stds=np.sqrt(np.diag(varpreds))
modelfits=np.column_stack((ypreds-stds*2,ypreds-stds,ypreds,ypreds+stds,ypreds+stds*2,model.mean.get_value(t)))
else:
ypreds = model.get_value(t)
stds=np.nanstd(lc[:,1]),len(t)*np.sqrt(len(lc[:,0]))
modelfits=np.column_stack((ypreds-stds*2,ypreds-stds,ypreds,ypreds+stds,ypreds+stds*2,ypreds))
#model.mean.get_value(t)
else:
modelfits=prevmodels
if residuals:
#Subtracting bestfit model from both flux and model to give residuals
newmodelfits=np.column_stack((modelfits[:,:5]-np.tile(modelfits[:,2], (5, 1)).swapaxes(0, 1),modelfits[:,5])) #subtracting median fit
Ploty=lc[:,1]-modelfits[:, 2][(np.round((lc[:,0]-lc[0,0])/0.020431700249901041)).astype(int)]
#p.xlim([t[np.where(redfits[:,2]==np.min(redfits[:,2]))]-1.6, t[np.where(redfits[:,2]==np.min(redfits[:,2]))]+1.6])
elif subGP:
newmodelfits=np.column_stack((modelfits[:,:5]-np.tile(modelfits[:,5], (5, 1)).swapaxes(0, 1),modelfits[:,5])) #subtracting median fit
Ploty=lc[:,1]-modelfits[:,5][(np.round((lc[:,0]-lc[0,0])/0.020431700249901041)).astype(int)]
#p.xlim([t[np.where(redfits[:,2]==np.min(redfits[:,2]))]-1.6, t[np.where(redfits[:,2]==np.min(redfits[:,2]))]+1.6])
else:
Ploty=lc[:,1]
newmodelfits=np.copy(modelfits)
if plot:
plt.errorbar(lc[:, 0], Ploty, yerr=lc[:, 2], fmt=',',color='#999999',alpha=0.8,zorder=-100)
plt.plot(lc[:, 0], Ploty, '.',color='#333399')
#Plotting 1-sigma error region and models
plt.fill(np.hstack((t,t[::-1])),
np.hstack((newmodelfits[:,2]-(newmodelfits[:,2]-newmodelfits[:,1]),(newmodelfits[:,2]+(newmodelfits[:,3]-newmodelfits[:,2]))[::-1])),
'#3399CC', linewidth=0,label=r'$1-\sigma$ region ('+str(scale*100)+'% scaled)')
#if not residuals:
# #Plotting fill from transit-less model:
# plt.fill(np.hstack((t,t[::-1])),
# np.hstack(((1.0+newmodelfits[:,2]-newmodelfits[:,5])-(newmodelfits[:,2]-newmodelfits[:,1]),((1.0+newmodelfits[:,2]-newmodelfits[:,5])+(newmodelfits[:,3]-newmodelfits[:,2]))[::-1])),
# '#66BBCC', linewidth=0,label='$1-\sigma$ region without transit')
plt.plot(t,newmodelfits[:,2],'-',color='#003333',linewidth=2.0,label='Median model fit')
if not residuals and not subGP and GP:
plt.plot(t,model.mean.get_value(t),'--',color='#003333',linewidth=2.0,label='Median transit model fit')
elif not residuals and not subGP and not GP:
plt.plot(t,model.get_value(t),'--',color='#003333',linewidth=2.0,label='Median transit model fit')
if not residuals and not subGP:
#Putting title on upper (non-residuals) graph
if title:
plt.title('Best fit model')
plt.legend(loc=2,fontsize=9)
if fname is not None:
plt.savefig(fname)
plt.xlim(np.min(lc[:,0]),np.max(lc[:,0]))
return modelfits
#def logclick(string,level='info'):
# #Function to both print string to terminal (with click) and log string to file.
# click.echo(string) if verbose else 0
# exec('logger.'+level+'(string)')
def RunShort(epic):
st=namaste.Star(str(epic),namaste.Settings(nsteps=30000,nthreads=4))
st.csvfile_dat('Best_Stellar_params_NoGRIZ.csv')
st.initLD()
st.addLightcurve('Lightcurves/EPIC'+epic+'_bestlc_ev.npy')
st.addGP()
st.Optimize_GP()
params=pd.DataFrame.from_csv('orb_params_sorted.csv')
#2121.02,0.5,0.0032
st.AddMonotransit(params.loc[int(epic),'cen'],params.loc[int(epic),'dur'],params.loc[int(epic),'dep'])
st.SaveAll()
st.RunMCMC()
st.PlotMCMC()
st.SaveMCMC()
if __name__=='__main__':
RunShort(sys.argv[1])
| 85,233 | 53.013942 | 252 | py |
Namaste | Namaste-master/namaste/planetlib.py | import numpy as np
import glob
import os
from os import path
import matplotlib
#matplotlib.use('Agg')
import pylab as plt
import logging
import astropy.io.fits as fits
import astropy.units as u
import astropy.coordinates as co
import pandas as pd
'''
Assorted scripts used by Namaste
'''
Namwd = path.dirname(path.realpath(__file__))
def FindTransitManual(kic, lc, cut=10):
'''
This uses the KIC/EPIC to
1) Get matching data
2) Display in pyplot window
3) Allow the user to find and type the single transit parameters
returns
# lightcurve (cut to 20Tdur long)
# 'guess' parameters''
'''
if lc==[]:
lc=getKeplerLC(kic)
plt.ion()
#PlotLC(lc, 0, 0, 0.1)
plt.figure(1)
plt.plot(lc[:,0],lc[:,1],'.')
print(lc)
print("You have 10 seconds to manouever the window to the transit (before it freezes).")
print("Sorry; matplotlib and raw_input dont work too well")
plt.pause(25)
Tcen=float(raw_input('Type centre of transit:'))
Tdur=float(raw_input('Type duration of transit:'))
depth=float(raw_input('Type depth of transit:'))
#Tcen,Tdur,depth=2389.7, 0.35, 0.0008
plt.clf()
return np.array((Tcen, Tdur, depth))
def getKeplerLC(kic, getlc=True, dirout=Namwd+'/KeplerFits/'):
'''
This module uses the KIC of a planet candidate to download lightcurves to a folder (if it doesnt already exist)
Default here is 'Namaste/KeplerFits/KIC'
Input: EPIC or KIC
Output: Lightcurve (if getlc=true, as deault) or string for file location
Args:
kic: EPIC (K2) or KIC (Kepler) id number
getlc: return directly the lightcurve or simply the file location
dirout: directory to save new fits files to
Returns:
lightcurve or lightcurve file location
'''
if str(int(kic)).zfill(9)[0]=='2':
#K2 File
fout=K2Lookup(kic)
if fout=='':
for camp in range(6):
# https://archive.stsci.edu/pub/k2/lightcurves/cN/XXXX00000/YY000
fname='ktwo'+str(int(kic))+'-c'+str(camp)+'_llc.fits'
#loc=pl.K2Lookup(kic)
fout=dirout+fname
if not os.path.exists(fout):
print('Downloading K2 file from MAST...')
comm='wget -q -nH --cut-dirs=6 -r -l0 -c -N -np -R \'index*\' -erobots=off https://archive.stsci.edu/pub/k2/lightcurves/c'+str(camp)+'/'+str(np.round(int(kic),-5))+'/'+str(np.round(kic-np.round(int(kic),-5),-3))+'/'+fout
os.system(comm)
#os.system('mv '+fname+' '+fout)
print('Downloaded lightcurve to '+fout)
if getlc:
lc,mag=ReadLC(fout)
return lc,mag
else:
#returns directory
return fout
else:
#Kepler File
dout=dirout+str(kic)+'/'
if not os.path.exists(dout):
#Downloading Kepler data if not already a folder
os.system('mkdir '+dout)
print('Downloading Kepler files from MAST...')
comm='wget -q -nH --cut-dirs=6 -r -l0 -c -N -np -R \'index*\' -erobots=off http://archive.stsci.edu/pub/kepler/lightcurves/'+str(int(kic)).zfill(9)[0:4]+'/'+str(int(kic)).zfill(9)+'/'
os.system(comm)
os.system('mv kplr'+str(int(kic)).zfill(9)+'* '+dout)
#print "Moving files to new directory"
print('Done downloading.')
#Removing short-cadence data:
for file in glob.glob(dout+'*slc.fits'):
os.system('rm '+file)
print('removing short cadence file '+str(file))
if getlc:
print(dout)
#Stitching lightcurves together
return ReadLC(dout)
else:
#Using final file from loop
return file
def VandDL(camp,epic,fitsfolder,v=1,returnradecmag=False):
from urllib.request import urlopen
urlfitsname='http://archive.stsci.edu/missions/hlsp/k2sff/c'+str(camp)+'/'+str(epic)[:4]+'00000/'+str(epic)[4:]+'/hlsp_k2sff_k2_lightcurve_'+str(epic)+'-c'+str(camp)+'_kepler_v'+str(int(v))+'_llc.fits'.replace(' ','')
#http://archive.stsci.edu/missions/hlsp/k2sff/c03/205800000/91876/hlsp_k2sff_k2_lightcurve_205891876-c03_kepler_v1_llc.fits
#http://archive.stsci.edu/missions/hlsp/k2sff/c00/202000000/89984/hlsp_k2sff_k2_lightcurve_202089984-c00_kepler_v1_llc-default-aper.txt
print(urlfitsname)
if not path.exists(fitsfolder+urlfitsname.split('/')[-1]):
ret = urlopen(urlfitsname)
print(ret.code)
if ret.code == 200:
f=fits.open(urlfitsname)
print("writing to "+fitsfolder+urlfitsname.split('/')[-1])
f.writeto(fitsfolder+urlfitsname.split('/')[-1])
else:
f=fits.open(fitsfolder+urlfitsname.split('/')[-1])
if returnradecmag:
return [f[0].header['RA_OBJ'],f[0].header['DEC_OBJ'],f[0].header['KEPMAG']]
return OpenFits(f,fitsfolder+urlfitsname.split('/')[-1])
def noneg_GetAssymDist(inval,uperr,derr,nd=5000,Nnegthresh=0.001):
neg=np.tile(True,nd)
retdist=np.zeros(nd)
Nnegs=nd
while Nnegs>Nnegthresh*nd:
retdist[neg]=GetAssymDist(inval,uperr,derr,Nnegs,returndist=True)
neg=retdist<0
Nnegs=np.sum(neg)
return abs(retdist)
def GetAssymDist(inval,uperr,derr,nd=5000,returndist=False):
derr=abs(derr)
#Up and Down errors indistinguishable, returning numpy array:
if abs(np.log10(uperr/derr)-1.0)<0.05:
if returndist:
return np.random.normal(inval,0.5*(uperr+derr))
else:
return inval, uperr,derr
else:
#Fitting some skew to the distribution to match up/down errors.
if derr>uperr:
minusitall=True
derr,uperr=uperr,derr
else:
minusitall=False
mult= -1.0 if inval<0.0 else 1.0
inval=mult*inval
val = derr*3 if inval>derr*3 else inval
plushift= 2.5*derr if val<1.2*derr else 0
val+=plushift
#finding n exponent for which power to this produces equidistant errors
findn = lambda n : abs(1.0-(((val+uperr)**(n)-(val)**(n))/((val)**(n)-(val-derr)**(n))))
import scipy.optimize as op
res=op.minimize(findn,0.5)
try:
dist=np.random.normal(val**(res.x),abs((val**(res.x))-(val-derr)**(res.x)),nd)**(1.0/res.x)
n=0
if np.sum(np.isnan(dist))!=nd:
while np.sum(np.isnan(dist))>0 or n>10:
dist[np.isnan(dist)]=np.random.normal(val**(res.x),abs((val**(res.x))-(val-derr)**(res.x)),np.sum(np.isnan(dist)))**(1.0/res.x)
n+=1
#print np.sum(np.isnan(dist))
#print str(derr)+' vs '+str(np.median(dist)-np.percentile(dist,16))+" | "+str(uperr)+' vs '+str(np.percentile(dist,84)-np.median(dist))
if plushift!=0:
dist-=plushift
if minusitall:
dist=-1*(dist-val)+val
dist=mult*(dist+inval-derr*3) if inval>derr*3 else mult*(dist)
if returndist:
return dist
else:
if mult==-1:
return [np.median(dist),np.percentile(dist,84)-np.median(dist),np.median(dist)-np.percentile(dist,16)]
else:
return [np.median(dist),np.median(dist)-np.percentile(dist,16),np.percentile(dist,84)-np.median(dist)]
else:
raise ValueError()
except:
return np.zeros(3)
def CalcDens(Star,nd=6000,returnpost=False,overwrite=True):
#Returns density from StarDat (in form T,Te1,Te2,R,Re1,Re2,M,Me1,Me2,opt:[logg,logge1,logge2,dens,dense1,dense2])
dens1 = lambda logg,rad: np.power(10,logg-2.0)*(4/3.0*np.pi*6.67e-11*(rad*695500000))**-1.0
dens2 = lambda mass,rad: (1.96e30*mass)/(4/3.0*np.pi*(695500000*rad)**3)
if not hasattr(Star,'srads'):
srads= GetAssymDist(Star.srad,Star.sraduerr,Star.sradderr,nd=nd,returndist=True)
else:
srads=Star.srads
print(srads)
srads[srads<0]=abs(np.random.normal(Star.srad,0.25*(Star.sraduerr+Star.sradderr),np.sum(srads<0)))
if hasattr(Star,'sdens') and not overwrite:
if returnpost and not hasattr(Star,'sdenss'):
densdist=GetAssymDist(Star.dens,Star.sdensuerr,Star.sdensderr,nd=nd,returndist=True)
return densdist
elif returnpost and hasattr(Star,'sdenss'):
return getattr(Star,'sdenss')
else:
return Star.sdens,Star.sdensuerr,Star.sdensderr
elif hasattr(Star,'slogg')==12:
#Returns a density as the weighted average of that from logg and mass
if not hasattr(Star,'sloggs'):
sloggs= GetAssymDist(Star.slogg,Star.slogguerr,Star.sloggderr,nd=nd,returndist=True)
else:
sloggs=Star.sloggs
d1=np.array([dens1(sloggs[l],srads[l]) for l in range(nd)])
stdd1=np.std(d1)
elif hasattr(Star,'smass'):
stdd1=np.inf
if not hasattr(Star,'sloggs'):
smasss= GetAssymDist(Star.smass,Star.smassuerr,Star.smassderr,nd=nd,returndist=True)
else:
smasss=Star.smasss
smasss[smasss<0]=abs(np.random.normal(Star.smass,0.25*(Star.smassuerr+Star.smassderr),np.sum(smasss<0)))
d2=np.array([dens2(smasss[m],srads[m]) for m in range(nd)])
#Using distribution with smallest std...
post=d1 if stdd1<np.std(d2) else d2
post/=1409 #Making solar density
if returnpost:
return post
else:
dens=np.percentile(post,[16,50,84])
return np.array([dens[1],np.diff(dens)[0],np.diff(dens)[1]])
def dens(StarDat,nd=6000,returnpost=False):
_,_,_,rad,raderr1,raderr2,mass,masserr1,masserr2,logg,loggerr1,loggerr2=StarDat
#Returns a density as the weighted average of that from logg and mass
dens1 = lambda logg,rad: np.power(10,logg-2.0)*(4/3.0*np.pi*6.67e-11*(rad*695500000))**-1.0
dens2 = lambda mass,rad: (1.96e30*mass)/(4/3.0*np.pi*(695500000*rad)**3)
d1_up=dens1(np.random.normal(logg,loggerr2,nd),np.random.normal(rad,raderr1,nd))
d1_dn=dens1(np.random.normal(logg,loggerr1,nd),np.random.normal(rad,raderr2,nd))
d2_up=dens2(np.random.normal(mass,masserr2,nd),np.random.normal(rad,raderr1,nd))
d2_dn=dens2(np.random.normal(mass,masserr1,nd),np.random.normal(rad,raderr2,nd))
#Combining up/down dists alone for up.down uncertainties. COmbining all dists for median.
#Gives almost identical values as a weighted average of resulting medians/errors.
print("logg/rad: "+str(np.median(np.vstack((d1_dn,d1_up))))+", mass/rad:"+str(np.median(np.vstack((d2_dn,d2_up))))+"")
if returnpost:
#Returning combined posterier...
#This has the problem of down errors being present in upwards errors (which may be less...)
post=np.vstack((d2_dn,d1_dn,d2_up,d1_up))
return post
else:
dens=[np.percentile(np.vstack((d2_dn,d1_dn)),16),np.median(np.vstack((d2_dn,d2_up,d1_up,d1_dn))),np.percentile(np.vstack((d2_up,d1_up)),84)]
return np.array([dens[1],np.diff(dens)[0],np.diff(dens)[1]])
def dens2(logg,loggerr1,loggerr2,rad,raderr1,raderr2,mass,masserr1,masserr2,nd=6000,returnpost=False):
#Returns a density as the weighted average of that from logg and mass
dens1 = lambda logg,rad: (np.power(10,logg-2)/(1.33333*np.pi*6.67e-11*rad*695500000))/1410.0
dens2 = lambda mass,rad: ((mass*1.96e30)/(4/3.0*np.pi*(rad*695500000)**3))/1410.0
loggs= np.random.normal(logg,0.5*(loggerr1+loggerr2),nd)
rads= np.random.normal(rad,0.5*(raderr1+raderr2),nd)
rads[rads<0]=abs(np.random.normal(rad,0.25*(raderr1+raderr2),np.sum(rads<0)))
masses= np.random.normal(mass,0.5*(masserr1+masserr2),nd)
masses[masses<0]=abs(np.random.normal(mass,0.25*(masserr1+masserr2),np.sum(masses<0)))
d1=np.array([dens1(loggs[l],rads[l]) for l in range(nd)])
d2=np.array([dens2(masses[m],rads[m]) for m in range(nd)])
#Combining up/down dists alone for up.down uncertainties. COmbining all dists for median.
#Gives almost identical values as a weighted average of resulting medians/errors.
print("logg/rad: "+str(np.median(d1))+"+/-"+str(np.std(d1))+", mass/rad:"+str(np.median(d2))+"+/-"+str(np.std(d2)))
post=d1 if np.std(d1)<np.std(d2) else d2
if returnpost:
#Returning combined posterier...
return post
else:
dens=np.percentile(post,[16,50,84])
return np.array([dens[1],np.diff(dens)[0],np.diff(dens)[1]])
def SpecTypes(teff,logg,specarr):
#Takes teff and logg to give TRMl estimates...
spec = specarr.iloc[np.nanargmin(abs(np.log10(float(teff))-specarr.logT_V.values))].name
print(spec)
lums=['ZAMS','V','IV','III','II','Ib','Iab','Ia']
#print specarr.loc[spec,['logg_ZAMS','logg_V','logg_IV','logg_III','logg_II','logg_Ib','logg_Iab','logg_Ia']].values
#print abs(float(logg)-specarr.loc[spec,['logg_ZAMS','logg_V','logg_IV','logg_III','logg_II','logg_Ib','logg_Iab','logg_Ia']].values)
#print np.nanargmin(abs(float(logg)-specarr.loc[spec,['logg_ZAMS','logg_V','logg_IV','logg_III','logg_II','logg_Ib','logg_Iab','logg_Ia']].values))
if logg=='':
lum='V'
else:
lum = lums[np.nanargmin(abs(float(logg)-specarr.loc[spec,['logg_ZAMS','logg_V','logg_IV','logg_III','logg_II','logg_Ib','logg_Iab','logg_Ia']].values))]
TRMl= m(spec,lum)
TRMl2=[]
for i in TRMl:
TRMl2+=[[i[1],np.diff(i)[0],np.diff(i)[1]]]
return TRMl2
def getK2LCs(epic,camp,fitsfolder=Namwd):
if fitsfolder[-1]!='/':fitsfolder=fitsfolder+'/'
from urllib.request import urlopen
#VANDERBURG LC:
camp=str(camp)
try:
lcvand=[]
if len(camp)>3: camp=camp.split(',')[0]
if camp=='10':
camp='102'
elif camp=='et' or camp=='E':
camp='e'
#https://www.cfa.harvard.edu/~avanderb/k2/ep60023342alldiagnostics.csv
else:
camp=str(camp.zfill(2))
if camp=='09' or camp=='11':
lc=np.zeros((3,3))
#C91: https://archive.stsci.edu/missions/hlsp/k2sff/c91/226200000/35777/hlsp_k2sff_k2_lightcurve_226235777-c91_kepler_v1_llc.fits
url1='http://archive.stsci.edu/missions/hlsp/k2sff/c'+str(int(camp))+'1/'+str(epic)[:4]+'00000/'+str(epic)[4:]+'/hlsp_k2sff_k2_lightcurve_'+str(epic)+'-c'+str(int(camp))+'1_kepler_v1_llc.fits'
if not path.exists(fitsfolder+url1.split('/')[-1]):
f1=fits.open(url1)
f1.writeto(fitsfolder+url1.split('/')[-1])
print("C91 downloaded and saved...")
else:
f1=fits.open(fitsfolder+url1.split('/')[-1])
url2='http://archive.stsci.edu/missions/hlsp/k2sff/c'+str(int(camp))+'2/'+str(epic)[:4]+'00000/'+str(epic)[4:]+'/hlsp_k2sff_k2_lightcurve_'+str(epic)+'-c'+str(int(camp))+'2_kepler_v1_llc.fits'
if not path.exists(fitsfolder+url2.split('/')[-1]):
f2=fits.open(url2)
f2.writeto(fitsfolder+url2.split('/')[-1])
else:
print('opening from '+fitsfolder+url2.split('/')[-1])
f2=fits.open(fitsfolder+url2.split('/')[-1])
lcvand=OpenFits(f1,fitsfolder+url1.split('/')[-1])[0]
lcvand=np.vstack((lcvand,OpenFits(f2,fitsfolder+url1.split('/')[-1])[0]))
elif camp=='e':
print("Engineering data")
#https://www.cfa.harvard.edu/~avanderb/k2/ep60023342alldiagnostics.csv
url='https://www.cfa.harvard.edu/~avanderb/k2/ep'+str(epic)+'alldiagnostics.csv'
df=pd.read_csv(url,index_col=False)
lcvand=np.column_stack((df['BJD - 2454833'].values,df[' Corrected Flux'].values,np.tile(np.median(abs(np.diff(df[' Corrected Flux'].values))),df.shape[0])))
else:
print("Getting Vanderburg lc")
lcvand=VandDL(camp,epic,fitsfolder)[0]
except:
logging.debug("Cannot get Vanderburg LC")
lcpdc=[]
logging.debug("getting pdc")
try:
logging.debug(str(epic)+" + "+str(camp))
urlfilename1=''
if camp == 10:
#https://archive.stsci.edu/missions/k2/lightcurves/c1/201500000/69000/ktwo201569901-c01_llc.fits
urlfilename1='https://archive.stsci.edu/missions/k2/lightcurves/c102/'+str(epic)[:4]+'00000/'+str(epic)[4:6]+'000/ktwo'+str(epic)+'-c102_llc.fits'
else:
urlfilename1='https://archive.stsci.edu/missions/k2/lightcurves/c'+str(int(camp))+'/'+str(epic)[:4]+'00000/'+str(epic)[4:6]+'000/ktwo'+str(epic)+'-c'+str(camp).zfill(2)+'_llc.fits'#elif camp in ['e','et','0','1','2','3','9','00','01','02','09']:
# #NO LCs - TPFs only
# if camp in ['00','01','02']: camp=camp[1]
# if camp=='9' or camp=='09': camp = '92'
# urlfilename1='https://archive.stsci.edu/missions/k2/target_pixel_files/c'+str(camp)+'/'+str(epic)[:4]+'00000/'+str(epic)[4:6]+'000/ktwo'+str(epic)+'-c'+str(camp)+'_lpd-targ.fits.gz'
#TPFs: https://archive.stsci.edu/missions/k2/target_pixel_files/c0/202000000/72000/ktwo202072917-c00_lpd-targ.fits.gz
#ret = urllib2.urlopen(urlfilename1.replace(' ',''))
if not path.exists(fitsfolder+urlfilename1.split('/')[-1]):
f=fits.open(urlfilename1.replace(' ',''))
print('writing to '+fitsfolder+urlfilename1.split('/')[-1])
f.writeto(fitsfolder+urlfilename1.split('/')[-1])
else:
print('opening from '+fitsfolder+urlfilename1.split('/')[-1])
f=fits.open(fitsfolder+urlfilename1.split('/')[-1])
if urlfilename1[-9:]=='_llc.fits':
print('opening PDC file...')
lcpdc=OpenFits(f,fitsfolder+urlfilename1.split('/')[-1])[0]
except:
logging.debug("Cannot get PDC LC")
lcev=[]
try:
import everest
#logging.debug("getting lc from everest for "+str(epic))
st=everest.Everest(int(epic))
lcev=np.column_stack((st.time,st.flux,st.fraw_err))
#logging.debug(str(len(lcev))+"-long lightcurve from everest")
lcev=lcev[nonan(lcev)]
lcev=lcev[CutAnomDiff(lcev[:,1])]
lcev[:,1:]/=np.median(lcev[:,1])
except:
logging.debug("Cannot get Everest LC")
return lcvand,lcpdc,lcev
def K2Lookup(EPIC, fname=Namwd+'/EPIC_FileLocationTable.txt'):
'''
Finds the filename and location for any K2 EPIC (ID)
Args:
EPIC: K2 epic number
fname: location of table of filelocations. HPO-specific currently.
Returns:
filename
'''
import glob
if not path.exists('EPIC_FileLocationTable.txt'):
direct=raw_input('Please enter the directory location of K2 lightcurves:')
if direct!='':
f=open(Namwd+'/EPIC_FileLocationTable.txt', 'wa')
#printing location and EPIC to file in Namaste directory
for file in glob.glob(direct+'/ktwo?????????-c??_?lc.fits'):
f.write(file.split('/')[-1][4:13]+','+file+'\n')
else:
return ''
if path.exists(fname):
EPIC=str(EPIC).split('.')[0]
tab=np.genfromtxt(fname, dtype=str)
if EPIC in tab[:, 0]:
file=tab[np.where(tab[:,0]==EPIC)[0][0]][1]
else:
print('No K2 EPIC in archive.')
file=''
return file
else:
return ''
def getLDs(Ts,feh=0.0,logg=4.43812,VT=2.0,mission='Kepler',type='Quadratic'):
'''
T_effs from 2500 to 40000
types= linear, Quadratic, 3par, 4par
'''
import pandas as pd
import scipy.interpolate
mission='Kepler';logg=4.0
if mission=='Kepler' or mission=='kepler' or mission=='K2' or mission=='k2':
lds=pd.read_fwf('http://www.astro.ex.ac.uk/people/sing/LDfiles/LDCs.Kepler.Table2.txt',header=6,index_col=False,widths=[8,8,8,9,9,9,9,9,9,9,9,9,9])
lds=lds.iloc[4:]
elif mission=='CoRoT' or mission=='Corot' or mission=='corot':
lds=pd.read_fwf('http://www.astro.ex.ac.uk/people/sing/LDfiles/LDCs.CoRot.Table1.txt',header=7,index_col=False,widths=[8,8,8,9,9,9,9,9,9,9,9,9,9])
lds=lds.iloc[4:]
else:
logging.error('Mission must be Kepler or Corot')
#Finding nearest logg and FeH...
loggs=pd.unique(lds['Log g'])[~pd.isnull(pd.unique(lds['Log g']))].astype(float)
fehs=pd.unique(lds['[M/H]'])[~pd.isnull(pd.unique(lds['[M/H]']))].astype(float)
logg=loggs[np.argmin(abs(logg-loggs))]
feh=fehs[np.argmin(abs(feh-fehs))]
lds=lds[(lds['Log g'].astype(float)==logg)*(lds['[M/H]'].astype(float)==feh)]
typecols=[['linear','Quadratic','3par','4par'],[['linear'],['Quadr','atic'],['3 para','meter non','-linar'],['4','parameter','non-line','ar']]]
if type not in typecols[0]:
logging.error('LD type not recognised')
else:
n=np.where(np.array(typecols[0])==type)[0]
cols=typecols[1][n]
ldouts=[]
for i in cols:
us=scipy.interpolate.interp1d(lds['T_eff'].astype(float),lds[i].astype(float))
ldouts+=[us(float(Ts))]
return ldouts
def LinearLDs(teff,teff_err1=200,teff_err2=200,logg=4.43,logg_err1=0.4,logg_err2=0.4,feh=0.0,mission='Kepler'):
if mission=='Kepler' or mission=='kepler' or mission=='K2' or mission=='k2':
lds=pd.read_fwf('http://www.astro.ex.ac.uk/people/sing/LDfiles/LDCs.Kepler.Table2.txt',header=6,index_col=False,widths=[8,8,8,9,9,9,9,9,9,9,9,9,9])
lds=lds.iloc[4:-1]
elif mission=='CoRoT' or mission=='Corot' or mission=='corot':
lds=pd.read_fwf('http://www.astro.ex.ac.uk/people/sing/LDfiles/LDCs.CoRot.Table1.txt',header=7,index_col=False,widths=[8,8,8,9,9,9,9,9,9,9,9,9,9])
lds=lds.iloc[4:-1]
if np.isnan(feh):
feh=0.0
from scipy.interpolate import CloughTocher2DInterpolator as ct2d
print(feh)
fehs=pd.unique(lds['[M/H]'])[~pd.isnull(pd.unique(lds['[M/H]']))].astype(float)
feh=fehs[np.nanargmin(abs(feh-fehs))]
lds=lds[pd.to_numeric(lds['[M/H]'])==feh]
xys=[(lds[['T_eff']].values.astype(float)[i][0],lds[['Log g']].values.astype(float)[i][0]) for i in range(lds.shape[0])]
u1int=ct2d(xys,lds[['Quadr']].values.astype(float))
u2int=ct2d(xys,lds[['atic']].values.astype(float))
print("Teff = "+str(teff)+" | logg = "+str(logg))
print(u1int(teff,logg))
print(u2int(teff,logg))
nd=6000
teffs=[np.random.normal(teff,teff_err1,nd),np.random.normal(teff,teff_err2,nd)]
loggs=[np.random.normal(logg,logg_err1,nd),np.random.normal(logg,logg_err2,nd)]
distsld1=[]
distsld2=[]
for t in teffs:
for l in loggs:
distsld1+=[u1int(t[i],l[i]) for i in range(nd)]
distsld2+=[u2int(t[i],l[i]) for i in range(nd)]
distsld1=np.array(distsld1)
outlds1=np.percentile(distsld1[~np.isnan(distsld1)],[16,50,84])
distsld2=np.array(distsld2)
outlds2=np.percentile(distsld2[~np.isnan(distsld2)],[16,50,84])
return np.array([outlds1[1],np.diff(outlds1)[0],np.diff(outlds1)[1],outlds2[1],np.diff(outlds2)[0],np.diff(outlds2)[1]])
def getLDWITHERRs(Ts,feh=0.0,logg=4.43812,VT=2.0,mission='Kepler',type='Quadratic'):
'''
T_effs from 2500 to 40000
types= linear, Quadratic, 3par, 4par
'''
import pandas as pd
import scipy.interpolate
mission='Kepler';logg=4.0
if mission=='Kepler' or mission=='kepler' or mission=='K2' or mission=='k2':
lds=pd.read_fwf('http://www.astro.ex.ac.uk/people/sing/LDfiles/LDCs.Kepler.Table2.txt',header=6,index_col=False,widths=[8,8,8,9,9,9,9,9,9,9,9,9,9])
lds=lds.iloc[4:]
elif mission=='CoRoT' or mission=='Corot' or mission=='corot':
lds=pd.read_fwf('http://www.astro.ex.ac.uk/people/sing/LDfiles/LDCs.CoRot.Table1.txt',header=7,index_col=False,widths=[8,8,8,9,9,9,9,9,9,9,9,9,9])
lds=lds.iloc[4:]
else:
logging.error('Mission must be Kepler or Corot')
#Finding nearest logg and FeH...
loggs=pd.unique(lds['Log g'])[~pd.isnull(pd.unique(lds['Log g']))].astype(float)
fehs=pd.unique(lds['[M/H]'])[~pd.isnull(pd.unique(lds['[M/H]']))].astype(float)
logg=loggs[np.argmin(abs(logg-loggs))]
feh=fehs[np.argmin(abs(feh-fehs))]
lds=lds[(lds['Log g'].astype(float)==logg)*(lds['[M/H]'].astype(float)==feh)]
typecols=[['linear','Quadratic','3par','4par'],[['linear'],['Quadr','atic'],['3 para','meter non','-linar'],['4','parameter','non-line','ar']]]
if type not in typecols[0]:
logging.error('LD type not recognised')
else:
n=np.where(np.array(typecols[0])==type)[0]
cols=typecols[1][n]
ldouts=[]
for i in cols:
us=scipy.interpolate.interp1d(lds['T_eff'].astype(float),lds[i].astype(float))
ldouts+=[us(float(Ts))]
return ldouts
def getKeplerLDs(Ts,logFeH=0.0,logg=4.43812,VT=2.0, type='2'):
'''
# estimate Quadratic limb darkening parameters u1 and u2 for the Kepler bandpass
Args:
Ts: Stellar temp
logFeH: log(Fe/H)
logg: log of surface gravity in cgs
VT:
type: Type of limb darkening parameter requested.
1: linear, 2: quadratic, 3: cubic, 4: quintic
Returns:
Quadratic limb darkening parameters
'''
import scipy.interpolate
types={'1':[3],'2':[4, 5],'3':[6, 7, 8],'4':[9, 10, 11, 12]}
#print(label)
us=[0.0,0.0]
if types.has_key(type):
checkint = types[type]
#print(checkint)
else:
print("no key...")
arr = np.genfromtxt(Namwd+'/Tables/KeplerLDLaws.txt',skip_header=2)
#Rounding Logg and LogFe/H to nearest useable values
arr=np.hstack((arr[:, 0:3], arr[:, checkint]))
arr=arr[arr[:, 1]==float(int(logg*2+0.5))/2]
FeHarr=np.unique(arr[:, 2])
logFeH=FeHarr[find_nearest(FeHarr,logFeH)]
arr=arr[arr[:, 2]==logFeH]
if 3500.<Ts<35000.:
#Interpolating arrays for u1 & u2 against T.
OutArr=np.zeros(len(checkint))
for i in range(3, len(arr[0, :])):
us=scipy.interpolate.interp1d(arr[:, 0], arr[:, i])
OutArr[i-3]=us(Ts)
return OutArr
else:
print('Temperature outside limits')
return 0.0, 0.0
def k2f(lc, winsize=7.5, stepsize=0.3, niter=10):
'''
#Flattens any K2 lightcurve while maintaining in-transit depth.
Args:
lc: 3-column lightcurve
winsize: size of window over which to polyfit
stepsize: size of step each iteration
niter: number of iterations over which anomalous values are removed to improve Chi-Sq
Returns:
'''
import k2flatten as k2f
return k2f.ReduceNoise(lc,winsize=winsize,stepsize=stepsize,niter=niter)#,ReduceNoise(lc, winsize=winsize, stepsize=stepsize, niter=niter)
def find_nearest(arr,value):
'''
#Finds index of nearest matching value in an array
Args:
arr: Array to search for value in
value: Value
Returns:
index of the nearest value to that searched
'''
arr = np.array(arr)
#find nearest value in array
idx=(np.abs(arr-value)).argmin()
return idx
def ReadLC(fname):
'''
# Reads a Kepler fits file to outputt a 3-column lightcurve and header.
# It recognises the input of K2 PDCSAP, K2 Dave Armstrong's detrending, everest lightcurve, and Kepler lightcurves
INPUTS:
# filename
OUTPUT:
# Lightcurve in columns of [time, relative flux, relative flux error];
# Header with fields [KEPLERID,RA_OB,DEC_OBJ,KEPMAG,SAP_FLUX]
'''
import sys
logging.debug('fname = '+str(fname))
fnametrue=str(np.copy(fname))
logging.debug('fnametrue = '+str(fnametrue))
fname=fname.split('/')[-1]
logging.debug('fnametrue[-3] = '+str(fnametrue.split('/')[-3]))
#logging.debug('fname fing kepler = '+str(fname.find('kplr')))
try:
if fnametrue[-1]=='/':
logging.debug('Kepler file in KeplerFits folder')
#Looks for kepler, kplr or KOI in name
#If a load of lightcurves have been downloaded to the default folder, this sticks them all together:
lc=np.zeros((3, 3))
#Stitching lightcurves together
for file in glob.glob(fnametrue+'*llc.fits'):
newlc,mag=OpenLC(file)
logging.debug(str(newlc))
lc=np.vstack((lc, newlc))
return lc[3:, :], mag
except:
logging.info("Failed during Kepler file check. Trying to open as other file type")
try:
return OpenLC(fnametrue)
except:
logging.error('Cannot read lightcurve file')
def Pmin(Tcen,lc,Tdur):
return np.max(abs(Tcen-lc[:, 0]))-Tdur
def Vmax(dens,Tcen,lc,Tdur):
return 86400*(((dens*1411*8*np.pi**2*6.67e-11)/(Pmin*86400*3))**(1/3.0))
def OpenFits(f,fname):
if f[0].header['TELESCOP']=='Kepler':
mag=f[0].header['KEPMAG']
logging.debug('Kepler/K2 LC. Mag = '+str(mag))
if fname.find('k2sff')!=-1:
logging.debug('K2SFF file')#K2SFF (Vanderburg) detrending:
lc=np.column_stack((f[1].data['T'],f[1].data['FCOR'],np.tile(np.median(abs(np.diff(f[1].data['FCOR']))),len(f[1].data['T']))))
elif fname.find('everest')!=-1:
logging.debug('Everest file')#Everest (Luger et al) detrending:
lc=np.column_stack((f[1].data['TIME'],f[1].data['FLUX'],f[1].data['RAW_FERR']))
elif fname.find('k2sc')!=-1:
logging.debug('K2SC file')#K2SC (Aigraine et al) detrending:
lc=np.column_stack((f[1].data['time'],f[1].data['flux'],f[1].data['error']))
elif fname.find('kplr')!=-1 or fname.find('ktwo')!=-1:
logging.debug('kplr/ktwo file')
if fname.find('llc')!=-1 or fname.find('slc')!=-1:
logging.debug('NASA/Ames file')#NASA/Ames Detrending:
lc=np.column_stack((f[1].data['TIME'],f[1].data['PDCSAP_FLUX'],f[1].data['PDCSAP_FLUX_ERR']))
elif fname.find('XD')!=-1 or fname.find('X_D')!=-1:
logging.debug('Armstrong file')#Armstrong detrending:
lc=np.column_stack((f[1].data['TIME'],f[1].data['DETFLUX'],f[1].data['APTFLUX_ERR']/f[1].data['APTFLUX']))
else:
logging.debug("no file type for "+str(f))
elif f[0].header['TELESCOP']=='COROT':
try:
mag=f[0].header['MAGNIT_V']
if type(f[0].header['MAGNIT_V'])==str or np.isnan(f[0].header['MAGNIT_V']): mag=f[0].header['MAGNIT_R']
#If THE MAG_V COLUMN is broken, getting the R-mag
except:
mag=f[0].header['MAGNIT_R']
if f[0].header['FILENAME'][9:12]=='MON':
#CHJD=2451545.0
logging.debug('Monochrome CoRoT lightcurve')
lc=np.column_stack((f[1].data['DATEJD'],f[1].data['WHITEFLUX'],f[1].data['WHITEFLUXDEV']))
elif f[0].header['FILENAME'][9:12]=='CHR':
logging.debug('3-colour CoRoT lightcurve')
#Adding colour fluxes together...
lc=np.column_stack((f[1].data['DATEJD'],\
f[1].data['REDFLUX']+f[1].data['BLUEFLUX']+f[1].data['GREENFLUX'],\
f[1].data['GREENFLUXDEV']+f[1].data['BLUEFLUXDEV']+f[1].data['REDFLUXDEV']))
lc[lc[:,2]==0.0,2]+=np.median(lc[lc[:,2]>0.0,2])
#Adding this to make up for any times there are no errors at all...
if np.sum(np.isnan(lc[:,2]))>len(lc[:,2])*0.5:
lc[:,2]=np.tile(np.median(abs(np.diff(lc[:,1]))),len(lc[:,2]))
else:
logging.debug('Found fits file but cannot identify fits type to identify with')
return lc,mag
def OpenLC(fname):
'''#Opens lightcurve from filename. Works for:
* .fits files from Kepler (check OpenFits)
* .npy 3-column saved Lightcurves
* .txt 3-column saved Lightcurves
'''
fnametrue=str(np.copy(fname))
fname=fname.split('/')[-1]
if fname[-5:]=='.fits':
try:
f=fits.open(fnametrue)
except IOError:
#May have trailing
f=fits.open(fnametrue,ignore_missing_end=True)
logging.debug('Fits file')
lc,mag=OpenFits(f,fname)
elif fname[-3:]=='npy':
lc=np.load(fnametrue)
print(np.shape(lc))
if len(lc)==2:
lc=lc[0]
mag=11.9-2.5*np.log10(np.median(lc[lc[:,1]/lc[:,1]==1.0,1])/313655.0)
elif fname[-3:]=='txt':
logging.debug('Found text file. Unpacking with numpy')
lc=np.genfromtxt(fnametrue)
mag=11.9-2.5*np.log10(np.median(lc[lc[:,1]/lc[:,1]==1.0,1])/313655.0)
try:
#removing nans
lc=lc[np.logical_not(np.isnan(np.sum(lc,axis=1)))]
#normalising flux and flux errs:
lc[:,1:]/=np.median(lc[:,1])
return lc, mag
except:
logging.error("No Lightcurve")
return None
def Test():
return 50
def OpenK2_DJA(fnametrue):
a = fits.open(fnametrue)
Nonans=[np.isnan(a[1].data['TIME'])==0]
time=(a[1].data['TIME'])[Nonans]
flux=(a[1].data['DETFLUX'])[Nonans]
flux_err=(a[1].data['DETFLUX_ERR'])[Nonans]
#((a[1].data['APTFLUX'][Nonans])/np.median(a[1].data['APTFLUX'][Nonans]))*(a[1].data['APTFLUX_ERR'][Nonans]/a[1].data['APTFLUX'][Nonans])
if np.isnan(flux_err).sum()==len(flux_err):
flux_err=np.sqrt(a[1].data['APTFLUX'][Nonans])/a[1].data['APTFLUX'][Nonans]*flux
Lc=np.column_stack(((a[1].data['TIME']), flux, flux_err/flux))
Lc=Lc[np.isnan(Lc.sum(axis=1))==0, :]
#TCEN=14
#FORMAT: KEPID, RA, DEC, KEPMAG, MEDFLUX
header = np.array([a[0].header['KEPLERID'],a[0].header['RA_OBJ'],a[0].header['DEC_OBJ'],a[0].header['KEPMAG'],np.median(a[1].data['APTFLUX'][Nonans])])
#DOING POLY FIT TO BOTH HALFS OF CAMPAIGN 1 DATA
return Lc, np.array(header.split(','))
def OpenK2_PDC(fnametrue):
a = fits.open(fnametrue)
time=(a[1].data['TIME'])
flux=(a[1].data['PDCSAP_FLUX'])
flux_err=(a[1].data['PDCSAP_FLUX_ERR'])
Lc=np.column_stack(((a[1].data['TIME']), flux, flux_err))
Nonans=[np.isnan(Lc.sum(axis=1))==0]
Lc=Lc[Nonans]
med=np.median(Lc[:, 1])
Lc[:, 1]/=med
Lc[:, 2]/=med
header = np.array([a[0].header['KEPLERID'],a[0].header['RA_OBJ'],a[0].header['DEC_OBJ'],a[0].header['KEPMAG'],np.median(a[1].data['PDCSAP_FLUX'][Nonans])])
return Lc, header
def OpenKepler(fnametrue):
a = fits.open(fnametrue)
time=(a[1].data['TIME'])
flux=(a[1].data['SAP_FLUX'])
flux_err=a[1].data['SAP_FLUX_ERR']
Lc=np.column_stack((time, flux, flux_err))
Nonans=np.logical_not(np.isnan(Lc.sum(axis=1)))
Lc=Lc[Nonans, :]
Lc[:, 2]=((Lc[:, 2])/np.median(Lc[:, 1]))
Lc[:, 1]/=np.median(Lc[:, 1])
Lc=Lc[np.prod(Lc, axis=1)!=0, :]
header = np.array([a[0].header['KEPLERID'],a[0].header['RA_OBJ'],a[0].header['DEC_OBJ'],a[0].header['KEPMAG'],np.median(a[1].data['SAP_FLUX'][Nonans])])
return Lc, header
def TypefromT(T):
'''
# Estimates spectral type from Temperature
# Types A0 to G6 taken from Boyajian 2012. Other values taken from Unreferenced MS approximations
INPUTS:
Temp
OUTPUTS:
Spectral Type (string)
'''
defs=np.genfromtxt(Namwd+"specTypes.txt", dtype=[('N', 'f8'),('Spec', 'S4'), ('Temp', 'f8'), ('Tmax','f8')])
if T>35000 or T<3000:
logging.error("Stellar temperature outside spectral type limits")
return None
else:
Type=defs['Spec'][(find_nearest(defs['Temp'],T))]
return Type
def RfromT(Teff,Tefferr, lenn=10000, logg=4.43812,FeH=0.0):
'''
# Estimates radius from Temperature.
# From Boyajian 2012, and only valid below G0 stars
# For hotter stars, Torres (2010) is used
INPUTS:
Temp, Temp Error, (Nint, (logg, Fe/H)<-only for Torres calculation)
OUTPUTS:
Radius, Radius Error
'''
#Scaling Temp error up if extremely low
Tefferr=150 if Tefferr<150 else Tefferr
#Boyajian (2012) dwarf star relation (<5800K). Generates 10000 Teffs and puts through equation
if 3200<=Teff<=5600:
Teff=np.random.normal(Teff, Tefferr, lenn)
d, c, b, a=np.random.normal(-8.133, 0.226, lenn), np.random.normal(5.09342, 0.16745, lenn)*10**(-3), 10**(-7)*np.random.normal(-9.86602, 0.40672, lenn), np.random.normal(6.479643, 0.32429, lenn)*10**(-11)
#d, c, b, a=np.random.normal(-10.8828, 0.1355, lenn), np.random.normal(7.18727, 0.09468, lenn)*10**(-3), 10**(-6)*np.random.normal(-1.50957, 0.02155, lenn), np.random.normal(1.07572, 0.01599, lenn)*10**(-10)
R = d + c*Teff + b*Teff**2 + a*Teff**3
Rout, Routerr=np.median(R), np.average(abs(np.tile(np.median(R),2)-np.percentile(R, [18.39397206,81.60602794])))/np.sqrt(len(R))
return Rout, Routerr
#Old method from Torres. Now used for 5800K+
elif Teff>5600:
Teff=np.random.normal(Teff, Tefferr, lenn)
X= np.log10(Teff)-4.1
b=np.random.normal([2.4427, 0.6679, 0.1771, 0.705, -0.21415, 0.02306, 0.04173], [0.038, 0.016, 0.027, 0.13, 0.0075, 0.0013, 0.0082], (lenn,7))
logR = b[:, 0] + b[:, 1]*X + b[:, 2]*X**2 + b[:, 3]*X**3 + b[:, 4]*(logg)**2 + b[:, 5]*(logg)**3 + b[:,6]*FeH
R=10**logR
Rmed, Rerr=np.median(R), np.average(abs(np.median(R)-np.percentile(R, [18.39397206,81.60602794])))
return Rmed, Rerr
else:
logging.error("Temp too low")
def MfromR(R, Rerr, lenn=10000):
'''
# Estimates radius from Mass.
# From Boyajian 2012, and only technically valid below G0 stars, although most Kepler lcs are dwarfs.
INPUTS:
Radius, Radius Error, (Nint)
OUTPUTS:
Mass, Mass Error
'''
#Converting to solar radii if not alread
R=R/695500000 if R>1e4 else R
R=np.random.normal(R, Rerr, lenn)
#Coefficients from Boyajian
c, b, a=np.random.normal(0.0906, 0.0027, lenn), np.random.normal(0.6063, 0.0153,lenn), np.random.normal(0.3200, 0.0165, lenn)
#Calculating
M= (-b+np.sqrt(b**2-4*a*(c-R)))/(2*a)
return np.median(M), np.average(abs(np.median(M)-np.percentile(M, [18.39397206,81.60602794])))
def getStarDat(kic,file):
'''
# Uses photometric information in the Kepler fits file of each lightcurve to estimate Temp, SpecType, Radius & Mass
#Colours include B-V,V-J,V-H,V-K.
# V is estimated from g and r mag if available
# otherwise assumes KepMag=V (which is true for G-type stars, but diverges fot hotter/cooler stars)
# JHK magnitudes also calculated independant of Vmags (which are often inaccurate).
# Any disagreement is therefore obvious in Terr
INPUTS:
kplr filename
OUTPUTS:
StarData Object [T,Terr,R,Rerr,M,Merr]
'''
#Looking in datafile for K2 stars:
Ts=None;count=0
funcs=[ExoFopCat,K2Guess,KOIRead,FitsGuess,AstropyGuess,SetT]
#Five different ways to estimate temperature (the last one being, pick 5500K+/-1800...)
while Ts==None:
func=funcs[count]
Ts=func(str(kic),file)
#print func(str(kic),file)
count+=1
if len(Ts)<3:
R,Rerr=RfromT(Ts[0],Ts[1])
M,Merr=MfromR(R,Rerr)
return [Ts[0],Ts[1],Ts[1],R,Rerr,Rerr,M,Merr,Merr]
else:
#In the HuberCat func we get all the stardat...
return Ts
def HuberCat(kic,file):
try:
import requests
global dump
response=requests.get("https://exofop.ipac.caltech.edu/k2/download_target.php?id="+str(kic))
catfile=response.raw.read()
T=catfile[catfile.find('Teff'):catfile.find('Teff')+50].split()[1:]
R=catfile[catfile.find('Radius'):catfile.find('Radius')+50].split()[1:]
M=catfile[catfile.find('Mass'):catfile.find('Mass')+50].split()[1:]
return list(np.array([T[0],T[1],T[1],R[0],R[1],R[1],M[0],M[1],M[1]]).astype(float))
except:
return None
def HuberCat_2(kic,file=''):
#Strips online file for a given epic
#try:
import requests
if 1==1:
global dump
response=requests.get("https://exofop.ipac.caltech.edu/k2/download_target.php?id="+str(kic))
catfile=response.text
outdat=pd.DataFrame(index={"EPIC":int(kic)})
catsplit=catfile.split('\n')
MAG=-1000;mags=[]
STPS=-1000;stpars=[]
Aliases=[]
for row in catsplit:
row=str(row)
if row=='':
pass
elif row[0:7]=='Proposa':
a=row[13:].replace(' ','')
outdat['K2_Proposal']=a
elif row[0:7]=='Aliases':
a=row[13:].split(',')
for n in range(len(a)):
outdat['ALIAS'+str(n)]=a[n]
elif row[0:8]=='Campaign':
outdat['camp']=row[13:].split(',') #list of camps
elif row[0:2]=='RA':
outdat['RA']=row[13:30].replace(' ','')
elif row[0:3]=='Dec':
outdat['Dec']=row[13:30].replace(' ','')
elif row.replace(' ','')=='MAGNITUDES:':
MAG=0
elif row.replace(' ','')=='STELLARPARAMETERS:':
MAG=-1000;STPS=0
elif row=='2MASS NEARBY STARS:':
STPS=-1000;MAG=-1000
elif row.replace(' ','')=='SPECTROSCOPY:':
STPS=-1000
outdat['Notes']='fu_spectra'
if MAG>1 and row!='':
a=row[18:50].split()
nom=row[0:17].replace(' ','')
outdat[nom]=float(a[0])
if len(a)>2: outdat[nom+'_ERR']=float(a[1])
if STPS>1 and row!='':
a=row[16:50].split()
nom=str(row[0:16]).translate(None, " (){}[]/")
nom='ExoFOP_ST_'+nom[:4]
if nom in outdat.columns: nom=nom+'_2'
outdat[nom]=float(a[0])
if len(a)>2: outdat[nom+'_ERR']=float(a[1])
MAG+=1;STPS+=1
return outdat
def HuberCat3(epic):
return pd.read_csv('http://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?&table=k2targets&format=csv&where=epic_number='+str(epic))
def ExoFop(kic):
if type(kic)==float: kic=int(kic)
import requests
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
response=requests.get("https://exofop.ipac.caltech.edu/k2/download_target.php?id="+str(kic))
catfile=response.text
arr=catfile.split('\n\n')
arrs=pd.Series()
for n in range(1,len(arr)):
if n==1:
df=pd.read_fwf(StringIO(arr[1]),header=None,widths=[12,90]).T
df.columns = list(df.iloc[0])
df = df.ix[1]
df.name=kic
df=df.rename(index={'RA':'rastr','Dec':'decstr','Campaign':'campaign'})
arrs=arrs.append(df)
elif arr[n]!='' and arr[n][:5]=='MAGNI':
sps=pd.read_fwf(StringIO(arr[2]),header=1,index=None).T
sps.columns = list(sps.iloc[0])
sps = sps.ix[1:]
sps=sps.rename(columns={'B':'mag_b','V':'mag_v','r':'mag_r','Kep':'kepmag','u':'mag_u','z':'mag_z','i':'mag_i','J':'mag_j','K':'mag_k','H':'mag_h','WISE 3.4 micron':'mag_W1','WISE 4.6 micron':'mag_W2','WISE 12 micron':'mag_W3','WISE 22 micron':'mag_W4'})
newarr=pd.Series()
for cname in sps.columns:
newarr[cname]=sps.loc['Value',cname]
newarr[cname+'_err1']=sps.loc['Uncertainty',cname]
newarr[cname+'_err2']=sps.loc['Uncertainty',cname]
newarr.name=kic
arrs=arrs.append(newarr)
elif arr[n]!='' and arr[n][:5]=='STELL':
sps=pd.read_fwf(StringIO(arr[n]),header=1,index=None,widths=[17,14,19,19,22,20]).T
#print sps
sps.columns = list(sps.iloc[0])
sps = sps.ix[1:]
#print sps
newarr=pd.Series()
#print sps.columns
sps=sps.rename(columns={'Mass':'mass','log(g)':'logg','Log(g)':'logg','Radius':'radius','Teff':'teff','[Fe/H]':'feh','Sp Type':'spectral_type','Density':'dens'})
for n,i in enumerate(sps.iteritems()):
if i[1]["User"]=='huber':
newarr[i[0]]=i[1]['Value']
newarr[i[0]+'_err']=i[1]['Uncertainty']
elif i[1]["User"]!='macdougall' and i[0] not in sps.columns[:n]:
#Assuming all non-Huber
newarr[i[0]+'_spec']=i[1]['Value']
newarr[i[0]+'_spec'+'_err']=i[1]['Uncertainty']
newarr.name=kic
#print newarr
arrs=arrs.append(newarr)
#print 'J' in arrs.index
#print 'WISE 3.4 micron' in arrs.index
elif arr[n]!='' and arr[n][:5]=='2MASS' and 'mag_J' not in arrs.index:
#print "SHOULDNT BE THIS FAR..."
sps=pd.read_fwf(StringIO(arr[n]),header=1)
#print sps.iloc[0]
sps=sps.iloc[0]
if 'rastr' not in arrs.index or 'decstr' not in arrs.index:
#Only keeping 2MASS RA/Dec if the ExoFop one is garbage/missing:
arrs['rastr']=sps.RA
arrs['decstr']=sps.Dec
elif arrs.rastr =='00:00:00' or arrs.decstr =='00:00:00':
arrs['rastr']=sps.RA
arrs['decstr']=sps.Dec
else:
sps.drop('RA',inplace=True)
sps.drop('Dec',inplace=True)
sps.drop('Pos Angle',inplace=True)
sps=sps.rename(index={'Designation':'Alias_2MASS','J mag':'mag_J','K mag':'mag_K','H mag':'mag_H','J err':'mag_J_err1','H err':'mag_H_err1','K err':'mag_K_err1','Distance':'2MASS_DIST'})
sps.name=kic
arrs=arrs.append(sps)
elif arr[n]!='' and arr[n][:5]=='WISE ' and 'mag_W1' not in arrs.index:
#print "SHOULDNT BE THIS FAR..."
sps=pd.read_fwf(StringIO(arr[n]),header=1,widths=[14,14,28,12,12,12,12,12,12,12,12,13,13])
#print sps.iloc[0]
sps= sps.iloc[0]
sps.drop('RA',inplace=True)
sps.drop('Dec',inplace=True)
sps.drop('Pos Angle',inplace=True)
#Band 1 mag Band 1 err Band 2 mag Band 2 err Band 3 mag Band 3 err Band 4 mag Band 4 err
sps=sps.rename(index={'Designation':'Alias_WISE','Band 1 mag':'mag_W1','Band 1 err':'mag_W1_err1','Band 2 mag':'mag_W2','Band 2 err':'mag_W2_err1','Band 3 mag':'mag_W3','Band 3 err':'mag_W3_err1','Band 4 mag':'mag_W4','Band 4 err':'mag_W4_err1','Distance':'WISE_DIST'})
sps.name=kic
arrs=arrs.append(sps)
arrs['StarComment']='Stellar Data from ExoFop/K2 (Huber 2015)'
arrs.drop_duplicates(inplace=True)
arrs['id']=kic
if 'kepmag' not in arrs.index or type(arrs.kepmag) != float or arrs.rastr=='00:00:00':
extra=HuberCat3(kic)
if ('k2_kepmag' in extra.index)+('k2_kepmag' in extra.columns)*(arrs.rastr!='00:00:00'):
arrs['kepmag']=extra.k2_kepmag
arrs['kepmag_err1']=extra.k2_kepmagerr
arrs['kepmag_err2']=extra.k2_kepmagerr
arrs['StarComment']='Stellar Data from VJHK color temperature and main seq. assumption'
else:
#No Kepmag in either ExoFop or the EPIC. Trying the vanderburg file...
try:
ra,dec,mag=VandDL('91',kic,Namwd,v=1,returnradecmag=True)
coord=co.SkyCoord(ra,dec,unit=u.degree)
arrs['rastr']=coord.to_string('hmsdms',sep=':').split(' ')[0]
arrs['decstr']=coord.to_string('hmsdms',sep=':').split(' ')[1]
arrs['kepmag']=mag
arrs['StarComment']='Stellar Data from VJHK color temperature and main seq. assumption'
except:
print("no star dat")
return None
if 'rastr' in arrs.index and 'decstr' in arrs.index and ('teff' not in arrs.index):#+(type(arrs.teff)!=float)):
teff,tefferr=AstropyGuess2(arrs.rastr,arrs.decstr)
arrs['teff']=teff
arrs['teff_err1']=tefferr
arrs['teff_err2']=tefferr
if 'radius' not in arrs.index:
if 'logg' not in arrs.index:
T,R,M,l,spec=StellarNorm(arrs['teff'],'V')
arrs['logg']=l[1]
arrs['logg_err']=np.average(np.diff(l))
arrs['StarComment']=arrs['StarComment']+". Assuming Main sequence"
else:
T,R,M,l,spec=StellarNorm(arrs['teff'],arrs['logg'])
arrs['StarComment']=arrs['StarComment']+". Using Lum Class from logg"
arrs['radius']=R[1]
arrs['radius_err']=np.average(np.diff(R))
arrs['mass']=M[1]
arrs['mass_err']=np.average(np.diff(M))
arrs['spectral_type']=spec
arrs['StarComment']=arrs['StarComment']+" R,M,etc from Teff fitting"
return arrs
def KeplerDat(kic):
return pd.read_csv('http://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?&table=keplerstellar&where=KepID='+str(kic)+'&format=csv&order=st_vet_date_str%20desc')
def KOIRead(kic,file):
if str(kic).zfill(8)[0]!=2:
try:
import pandas as pd
#One problem is that this table is not particularly up to date and has huge Radii errors...
koitable=pd.read_csv(Namwd+'/Tables/KeplerKOItable.csv',skiprows=155)
match=koitable[koitable['kepid']==int(kic)]
return list(abs(np.array([match['koi_steff'].values[0], match['koi_steff_err1'].values[0], match['koi_steff_err2'].values[0], match['koi_srad'].values[0], match['koi_srad_err1'].values[0], match['koi_srad_err2'].values[0], match['koi_smass'].values[0], match['koi_smass_err1'].values[0], match['koi_smass_err2'].values[0]])))
except:
return None
else:
return None
def SetT(kic,file):
return 5500,1800
def AstropyGuess(kic, file,ra=None,dec=None,kepmag=None):
#Searches 2MASS catalogue for JHK band fluxes and uses these to estimate a teff.
try:
import astropy.io.fits as fits
from astropy.vo.client import conesearch
from astropy import coordinates as co
from astropy import units as u
if path.exists(file):
a=fits.open(file)
ra,dec=a[0].header['RA_OBJ'], a[0].header['DEC_OBJ']
c=co.SkyCoord(ra*u.deg,dec*u.deg)
if type(a[0].header['GMAG'])==float and type(a[0].header['RMAG'])==float:
Vmag=float(a[0].header['GMAG']) - 0.58*(float(a[0].header['GMAG'])-float(a[0].header['RMAG'])) - 0.01
#Verr=((0.42*float(catdat[24]))**2+(0.58*float(catdat[26]))**2)**0.5
else:
#Assuming kepler mag is the same as V (correct for ~Gtype)
Vmag=a[0].header['KEPMAG']
elif ra!=None and dec!=None and kepmag!=None:
c=co.SkyCoord(ra,dec,frame='icrs')
Vmag=kepmag
#result = conesearch.conesearch(c, 0.025 * u.degree,catalog_db='2MASS All-Sky Point Source Catalog 2',verbose=False)
dists=np.sqrt((abs(c.ra.value-result.array['ra'])**2+(abs(c.ra.value-result.array['ra'])))**2)
mags=result.array['j_m']
nearest=np.argmin(dists/mags**2)
print("Found 2MASS source "+str(dists[nearest]*3600)+"\" away with Jmag "+str(mags[nearest]))
row = result.array.data[nearest]
T,Terr=coloursCheck(np.array([0, Vmag, row['j_m'],row['h_m'],row['k_m']]))
#print str(T)+" from 2MASS source"
return T,Terr
except:
return None
def AstropyGuess2(ra,dec):
from astroquery.vizier.core import Vizier
import astropy.coordinates as coord
import astropy.units as u
result = Vizier.query_region(coord.SkyCoord(ra, dec, unit=(u.hourangle, u.deg)),width="0d0m40s", height="0d0m40s",catalog=["NOMAD","allwise"])
nomadseps=coord.SkyCoord(ra, dec, unit=(u.hourangle, u.deg)).separation(coord.SkyCoord(result[0]['RAJ2000'],result[0]['DEJ2000']))
wiseseps=coord.SkyCoord(ra, dec, unit=(u.hourangle, u.deg)).separation(coord.SkyCoord(result[1]['RAJ2000'],result[1]['DEJ2000']))
print(str(np.min(nomadseps))+" < Nomad | Wise > "+str(np.min(wiseseps)))
wise=result[1][np.argmin(wiseseps)]
nomad=result[0][np.argmin(nomadseps)]
if 'e_Jmag' in wise.columns:
match=wise
colnames=['Bmag','Vmag','Rmag']
for c in range(3):
if colnames[c] in nomad.columns and type(nomad.columns[colnames[c]])==float:
match.table[colnames[c]]=nomad[colnames[c]]
match.table['e_'+colnames[c]]=nomad['r_'+colnames[c]]
return coloursCheck2(match)
def coloursCheck2(match,niter=1800):
import scipy.interpolate as interp
'''
#Estimate stellar Temperature from b,v,r,j,h,k magnitudes
Args:
mags: array of b,v,r,j,h,k magnitudes
Returns:
T : Stellar Temperature
Terr: Stellar Temperature error from the STD of the distribution of each temp estimate \
(to a minimum of 150K precision)
'''
phot=np.array(['B','V','R','J','H','K','W1','W2','W3','W4'])
photerrs=np.array(['e_'+p+'mag' for p in phot])
mask=np.zeros(len(phot)).astype(bool)
#Checking if the magnitude in the match is a float, else masking it out
for n in range(len(phot)):
try:
if float(match[phot[n]+'mag'])/float(match[phot[n]+'mag'])==1.0:
mask[n]=True
else:
print("no "+phot[n])
except:
print("no "+phot[n])
#Checking if the error is a valid float, otherwise setting err as 0.8
for err in photerrs[mask]:
try:
if float(match[err])/float(match[err])!=1.0:
match.table[err]=0.8
except:
#Need to remove the column to set a new one...
if err in match.columns:
match.table.remove_column(err)
match.table[err]=0.8
#Getting table
MScols=pd.DataFrame.from_csv(Namwd+"/Tables/ColoursTab3.txt")
#MScols=pd.read_table(Namwd+"/Tables/ColoursTab2.txt",header=20,delim_whitespace=True,na_values=['...','....','.....','......'])
order=['B-V','V-R','R-J','J-H','H-K','K-W1','W1-W2','W2-W3','W3-W4']#Good from B0 to K5 with Wise. Without Wise good to M8V
os=np.array([o.split('-') for o in order]).swapaxes(0,1)
cols=[]
#print phot[mask]
for p in range(np.sum(mask)-1):
#print phot[mask][p]+'-'+phot[mask][p+1]+" - "+str(float(match[phot[mask][p]+'mag'])-float(match[phot[mask][p+1]+'mag']))
col=phot[mask][p]+'-'+phot[mask][p+1]
cols+=[col]
if col not in MScols:
#Making it from others
if phot[mask][p] in os[0] and phot[mask][p+1] in os[1]:
#Adding column to MS cols df.
c0=np.where(os[0]==phot[mask][p])[0]
c1=np.where(os[1]==phot[mask][p+1])[0]
MScols[phot[mask][p]+'-'+phot[mask][p+1]]=np.sum(order[c0:c1])
else:
print("problem with "+phot[mask][p]+'-'+phot[mask][p+1])
T=np.zeros((len(cols),2))
for c in range(len(cols)):
func=interp.interp1d(MScols[cols[c]],MScols['logT'])
m1=float(match[cols[c].split('-')[0]+'mag'])
m2=float(match[cols[c].split('-')[1]+'mag'])
mag1s=np.random.normal(m1,float(match['e_'+cols[c].split('-')[0]+'mag']),niter)
mag2s=np.random.normal(m2,float(match['e_'+cols[c].split('-')[1]+'mag']),niter)
tT=[]
for n in range(niter):
try:
tT+=[func(mag1s[n]-mag2s[n])]
except:
tT+=[np.nan]
tT=np.array(tT)
tT=tT[~np.isnan(tT)]
if (len(tT)/float(niter))>0.5:
T[c,0]=np.median(tT)
T[c,1]=np.std(tT)
#print cols[c]+" - "+str(np.power(10,T[c,0]))
else:
T[c,0]=np.nan
T[c,1]=np.nan
T=T[~np.isnan(np.sum(T,axis=1))]
T[T[:,1]==0.0,1]=0.5
avT=np.average(T[:,0],weights=T[:,1]**-2)
sig=np.sqrt(np.average((T[:,0]-avT)**2,weights=T[:,1]**-2))
return np.power(10,avT),sig*np.power(10,avT)
'''
def getStarDat(kic,file=''):
# Uses photometric information in the Kepler fits file of each lightcurve to estimate Temp, SpecType, Radius & Mass
#Colours include B-V,V-J,V-H,V-K.
# V is estimated from g and r mag if available
# otherwise assumes KepMag=V (which is true for G-type stars, but diverges fot hotter/cooler stars)
# JHK magnitudes also calculated independant of Vmags (which are often inaccurate).
# Any disagreement is therefore obvious in Terr
#INPUTS:
#kplr filename
#OUTPUTS:
#StarData Object [T,Terr,R,Rerr,M,Merr]
#Looking in datafile for K2 stars:
if str(int(kic)).zfill(9)[0]=='2':
Ts = K2Guess(int(kic))
if Ts==None and file!='':
#Using the fits file
Ts=FitsGuess(file)
if Ts!=None:
R,Rerr=RfromT(Ts[0],Ts[1])
M,Merr=MfromR(R,Rerr)
return [Ts[0],Ts[1],R,Rerr,M,Merr]
#If a value from the above arrays is 2sigma out in temperature, cut...
else:
try:
import pandas as pd
#One problem is that this table is not particularly up to date and has huge Radii errors...
koitable=pd.read_csv(Namwd+'/Tables/KeplerKOItable.csv',skiprows=155)
match=koitable[koitable['kepid']==int(kic)]
return list(abs(np.array([match['koi_steff'].values[0], match['koi_steff_err1'].values[0], match['koi_steff_err2'].values[0], match['koi_srad'].values[0], match['koi_srad_err1'].values[0], match['koi_srad_err2'].values[0], match['koi_smass'].values[0], match['koi_smass_err1'].values[0], match['koi_smass_err2'].values[0]])))
except KeyError:
if file!='':
#Using the fits file
Ts=FitsGuess(file)
if Ts!=None:
R,Rerr=RfromT(Ts[0],Ts[1])
M,Merr=MfromR(R,Rerr)
return [Ts[0],Ts[1],R,Rerr,M,Merr]
logging.warning("Unable to get Star Data from catalogues or colours.")
#Does this kill the script here?
pass
'''
def FitsGuess(kic, file):
#Otherwise using fits colours
from astropy.io import fits
try:
lcfits=fits.open(file)
except ValueError:
print("Lightcurve is not a fits file and data not in EPIC/KIC catalogues.")
return None
Kepmag, gmag, rmag, imag, zmag, Jmag, Hmag, Kmag= lcfits[0].header['KEPMAG'], \
lcfits[0].header['GMAG'], lcfits[0].header['RMAG'], lcfits[0].header['IMAG'],\
lcfits[0].header['ZMAG'], lcfits[0].header['JMAG'], lcfits[0].header['HMAG'], lcfits[0].header['KMAG']
if type(gmag)==float and type(rmag)==float:
Vmag=float(gmag) - 0.58*(float(gmag)-float(rmag)) - 0.01
#Verr=((0.42*float(catdat[24]))**2+(0.58*float(catdat[26]))**2)**0.5
else:
#Assuming kepler mag is the same as V (correct for ~Gtype)
Vmag=Kepmag
try:
Temp,Terr= coloursCheck(np.array([0,Vmag, Jmag, Hmag, Kmag]))
return Temp,Terr
except:
return None
def coloursCheck(mags):
'''
#Estimate stellar Temperature from b,v,j,h,k magnitudes
Args:
mags: array of b,v,j,h,k magnitudes
Returns:
T : Stellar Temperature
Terr: Stellar Temperature error from the STD of the distribution of each temp estimate \
(to a minimum of 150K precision)
'''
mags=np.where(mags==0,np.nan,mags)
b,v,j,h,k=mags
cols=np.array([b-v,v-j,v-h,v-k,j-h,j-k])
nonan=np.arange(0,len(cols),1)[np.logical_not(np.isnan(cols))]
MScols=np.genfromtxt(Namwd+"/Tables/MainSeqColours.csv", delimiter=',')
coltab=np.column_stack(((MScols[:, 3]),(MScols[:, 6]),(MScols[:, 7]), \
(MScols[:, 8]), (MScols[:, 7])-(MScols[:, 6]), (MScols[:, 8])-(MScols[:, 6])))
T=np.zeros((len(cols)))
import scipy.interpolate
for c in nonan:
func=scipy.interpolate.interp1d(coltab[:,c],MScols[:, 14])
T[c]=func(cols[c])
T=T[T!=0]
#Returning median of temp and std (if std>150)
return np.median(T), np.std(T) if np.std(T)>150.0 else 150.0
def PlanetRtoM(Rad):
'''
# Estimate Planetary Mass from Radius.
# Adapted from Weiss & Marcy and extrapolated below/above distribution
# Could use the Kipping paper
Args:
Rad: Planet radius (in Rearths)
Returns:
Planet Mass in MEarth
'''
Rearth=6.137e6
Mearth=5.96e24
if type(Rad) is float or type(Rad) is int:
Rad=[Rad]
M=np.zeros_like(Rad)
M[Rad<=1.5]=((2430+3390*Rad[Rad<=1.5])*(1.3333*np.pi*(Rad[Rad<=1.5]*Rearth)**3))/Mearth
M[(Rad>1.5)*(Rad<=4.0)]=2.69*(Rad[(Rad>1.5)*(Rad<=4.0)]**0.93)
giants=(Rad>4.)*(Rad<=16.0)
if giants.sum()>0:
import scipy.interpolate
o=np.array([[3.99, 9.0,10.5,12.0,13.0,14.0,14.5, 15.5, 16.0],[10.0, 100.0,300.0,1000.0,1100.0,1200.0, 1350.0, 5000.0, 10000.0]])
f= scipy.interpolate.interp1d(o[0, :],o[1, :])
M[giants]=f(Rad[giants])
M[Rad>16.0]=333000*(Rad[Rad>16.0]/109.1)**1.5#(such that 1.5 ~10000.0)
return M
def PlotLC(lc, offset=0, col=0, fig=1, titl='Lightcurve', hoff=0, epic=0):
'''
This function plots a lightcurve (lc) in format: times, flux, flux_errs.
Offset allows multiple lightcurves to be displayed above each other. Col allows colour to be vaired (otherwise, grey)
Args:
lc: 3-column lightcurve (t,y,yerr)
offset: y-axis offset
col: color (matplotlib single-digit code or hexcolor)
fig: Figure number
titl: Title to plot
hoff: horizontal offset
epic: Lightcurve ID
Returns:
You return nothing, Jon Snow.
'''
import pylab as p
if epic==1:
#Doing lookup and get lc intrisincally
lc=ReadLC(K2Lookup(lc))[0]
#print "Plotting Lightcurve"
if col==0:
col='#DDDDDD'#'#28596C'
#col= '#'+"".join([random.choice('0123456789abcdef') for n in xrange(6)])
plt.ion(); plt.figure(fig); plt.title(titl);plt.xlabel('time');plt.ylabel('Relative flux');
plt.errorbar(lc[:, 0]+hoff, lc[:, 1]+offset, yerr=lc[:, 2], fmt='.',color=col)
def K2Guess(EPIC, colours=0, pm=0, errors=0):
'''#This module takes the K2 EPIC and finds the magnitudes from the EPIC catalogue. It then uses these to make a best-fit guess for spectral type, mass and radius
#It can also take just the B-V, V-J, V-H and V-K colours.
#Fitzgerald (1970 - A&A 4, 234) http://www.stsci.edu/~inr/intrins.html
#[N Sp. Type U-B (B-V) (V-R)C (V-I)C (V-J) (V-H) (V-K) (V-L) (V-M) (V-N) (V-R)J (V-I)J Temp Max Temp]
Returns:
# Spec Types, Temps, Radii, Masses.
'''
import csv
#ROWS: EPIC,RA,Dec,Data Availability,KepMag,HIP,TYC,UCAC,2MASS,SDSS,Object type,Kepflag,pmra,e_pmra,pmdec,e_pmdec,plx,e_plx,Bmag,e_Bmag,Vmag,e_Vmag,umag,e_umag,gmag,e_gmag,rmag,e_rmag,imag,e_imag,zmag,e_zmag,Jmag,e_Jmag,Hmag,e_Hmag,Kmag,e_Kmag
reader=csv.reader(open(Namwd+'/Tables/EPICcatalogue.csv'))
a=0
result={}
for row in reader:
if a>1:
key=row[0]
if key in result:
pass
result[key] = row[1:]
a+=1
try:
catdat=np.array(result[str(EPIC)])
except KeyError:
return None
catdat[np.where(catdat=='')]='0'
V=float(catdat[19])
Verr=float(catdat[20])
if V=='0' and 0 not in catdat[23:25]:
V=float(catdat[23]) - 0.58*(float(catdat[23])-float(catdat[25])) - 0.01
Verr=((0.42*float(catdat[24]))**2+(0.58*float(catdat[26]))**2)**0.5
#b,v,j,h,k COLOURS
mags=np.array((float(catdat[17]),V,float(catdat[31]),float(catdat[33]),float(catdat[35])))
return coloursCheck(mags)
def MS_approx(colours, pm=0, errors=0):
'''#If K2, finds magnitudes from EPIC catalogue.
#If CoRoT, uses online CoRoT database.
#If neither, uses astropy to search for NOMAD catalogue data
#It then uses these to make a best-fit guess for spectral type, mass and radius
#It can also take just the B-V, V-J, V-H and V-K colours.
#Fitzgerald (1970 - A&A 4, 234) http://www.stsci.edu/~inr/intrins.html
#[N Sp. Type U-B (B-V) (V-R)C (V-I)C (V-J) (V-H) (V-K) (V-L) (V-M) (V-N) (V-R)J (V-I)J Temp Max Temp]
Returns:
# Spec Types, Temps, Radii, Masses.
'''
import requests
global dump
#ROWS: EPIC,RA,Dec,Data Availability,KepMag,HIP,TYC,UCAC,2MASS,SDSS,Object type,Kepflag,pmra,e_pmra,pmdec,e_pmdec,plx,e_plx,Bmag,e_Bmag,Vmag,e_Vmag,umag,e_umag,gmag,e_gmag,rmag,e_rmag,imag,e_imag,zmag,e_zmag,Jmag,e_Jmag,Hmag,e_Hmag,Kmag,e_Kmag
if mission=='K2':
ExoFopCat(kic)
elif mission=='CoRoT':
tbd=0
reader=csv.reader(open(Namwd+'/Tables/EPICcatalogue.csv'))
a=0
result={}
for row in reader:
if a>1:
key=row[0]
if key in result:
pass
result[key] = row[1:]
a+=1
try:
catdat=np.array(result[str(EPIC)])
except KeyError:
return None
catdat[np.where(catdat=='')]='0'
V=float(catdat[19])
Verr=float(catdat[20])
if V=='0' and 0 not in catdat[23:25]:
V=float(catdat[23]) - 0.58*(float(catdat[23])-float(catdat[25])) - 0.01
Verr=((0.42*float(catdat[24]))**2+(0.58*float(catdat[26]))**2)**0.5
#b,v,j,h,k COLOURS
mags=np.array((float(catdat[17]),V,float(catdat[31]),float(catdat[33]),float(catdat[35])))
return coloursCheck(mags)
def CoRoTDat(id,returnlc=True,fitsfolder='.'):
import requests
global dump
#response=requests.get('http://cesam.oamp.fr/exodat/web-services/get-data-by-corot-id?catalog=exo2mass&corotid='+str(id)+'&header=true&format=csv')
response=requests.get('http://cesam.oamp.fr/exodat/web-services/get-data-by-corot-id?catalog=exo2mass&corotid='+str(id)+'&header=true&format=csv')
arr=response.text.encode('ascii','ignore').split('\n')
arr=np.vstack((np.array(arr[0].split(',')),np.array(arr[1].split(','))))
corotdf=pd.DataFrame(arr[1:],columns=arr[0])
response2=requests.get("http://cesam.oamp.fr/exodat/web-services/get-data-by-corot-id?catalog=observations&corotid="+str(id)+"&header=true&format=csv")
arr2=response2.text.encode('ascii','ignore').split('\n')
arr2=np.vstack(([arr2[n].split(',') for n in range(len(arr2))][:-1]))
obsdf=pd.DataFrame(arr2[1:],columns=arr2[0])
#response3=requests.get("http://cesam.oamp.fr/exodat/web-services/get-data-by-corot-id?catalog=obscat&corotid="+str(id)+"&header=true&format=csv")
#arr3=response3.text.encode('ascii','ignore').split('\n')
#arr3=np.vstack(([arr3[n].split(',') for n in range(len(arr3))][:-1]))
#obscatdf=pd.DataFrame(arr3[1:],columns=arr3[0])
#print obscatdf
if returnlc:
#Using the observations dataframe to get the lightcurve
fs,files=[],[]
for row in obsdf.iterrows():
f,fname=getCoRoTlc(row[1].run_id,row[1].corot_id,fitsfolder)
fs+=[f]
files+=[fname]
count=0
lc=np.zeros((300000,3))
#May be multiple fields observed...
for n in range(len(fs)):
templc,mag=OpenFits(fs[n],files[n])
templc=templc[nonan(templc)]
templc[:,1:]/=np.median(templc[:,1])
templc=templc[AnomMedianCut(templc,n=31,kind='high')]
lc[count:count+len(templc[:,0])]
count+=len(templc[:,0])
#Removing unused lightcurve rows
lc=lc[:count,:]
return lc, pd.concat([corotdf,obsdf], axis=1)
else:
if np.shape(obsdf)[0]==1:
return pd.concat([corotdf,obsdf], axis=1)
else:
df0= pd.concat([corotdf.iloc[0],obsdf.iloc[0]], axis=1)
return df0.append([pd.concat([corotdf.iloc[0],obsdf.iloc[n]], axis=0) for n in range(1,np.shape(obsdf)[0])])
#def getCoToRlc(obsdf):
def getCoRoTlc(field,corotid,fitsfolder='./'):
from urllib.request import urlopen
import astropy.io.fits as fits
poss_times_by_field=np.load('/Users/Hugh/ownCloud/PhD/K2/SingleTransits/CoRoT_wget_ts.npy')
possts=poss_times_by_field[poss_times_by_field[:,0]==field]
f=[];n=0
tinset='failed'
while n<len(possts):
tinsert=possts[n,2].replace('XXXXXXXXXX',str(corotid).zfill(10))
try:
urlfitsname="http://exoplanetarchive.ipac.caltech.edu/data/ETSS/corot_"+possts[n,1]+"/FITSfiles/"+field+"/"+tinsert+".fits"
ret = urlopen(urlfitsname)
if ret.code == 200:
if path.exists(fitsfolder+tinsert+".fits"):
f=fits.open(fitsfolder+tinsert+".fits")
else:
f=fits.open(urlfitsname)
f.writeto(fitsfolder+tinsert+".fits")
n+=100
else:
n+=1
#os.system("wget -O "+tinsert+".fits http://exoplanetarchive.ipac.caltech.edu/data/ETSS/corot_"+ft[1]+"/FITSfiles/"+field+"/"+tinsert+".fits -a corot_"+ft[1]+"_"+field+"_wget.log")
except:
#print "No luck with "+str(n)
n+=1
print(f)
#"wget -O AN2_STAR_"+obsdf.loc[0,"corot_id"]+"_20070203T130553_20070401T235518.fits http://exoplanetarchive.ipac.caltech.edu/data/ETSS/corot_exo/FITSfiles/"+field+"/EN2_STAR_MON_"+obsdf.loc[0,"corot_id"]+"_20070203T130553_20070401T235518.fits -a corot_exo_"+field+"_wget.log",\,\
#"wget -O AN2_STAR_"+obsdf.loc[0,"corot_id"]+"_20070203T130553_20070401T235518.fits http://exoplanetarchive.ipac.caltech.edu/data/ETSS/corot_exo/FITSfiles/"+field+"/EN2_STAR_MON_"+obsdf.loc[0,"corot_id"]+"_20070203T130553_20070401T235518.fits -a corot_exo_"+field+"_wget.log",\\
return f,fitsfolder+tinsert+".fits"
#for field in
#"wget -O EN2_STAR_MON_0102693924_20070203T130553_20070401T235518_lc.tbl http://exoplanetarchive.ipac.caltech.edu/data/ETSS/corot_exo/lightcurve/IRa01//EN2_STAR_MON_0102693924_20070203T130553_20070401T235518_lc.tbl -a corot_exo_IRa01_wget.log"
#%"wget -O EN2_STAR_MON_0102693924_20070203T130553_20070401T235518.fits http://exoplanetarchive.ipac.caltech.edu/data/ETSS/corot_exo/FITSfiles/IRa01/EN2_STAR_MON_0102693924_20070203T130553_20070401T235518.fits -a corot_exo_IRa01_wget.log"
def CoRoTStarPars(corotdf,specarr=None,retcomment=False):
#Loading array to compute stellar parameters from corot dataframe
#returns T,R,M,logg
#Always using values[0] - ie. assuming only the top line of the df has results
if type(specarr) is not pd.core.frame.DataFrame:
specarr=pd.DataFrame.from_csv('../TypeClassTable.csv')
out=[None,None]
if corotdf.color_temperature=='':
if corotdf.spectral_type!='' and corotdf.luminosity_class!='':
#row=specarr.loc[corotdf.spectral_type.values[0]]
StarDat=StellarNorm(corotdf.spectral_type,corotdf.luminosity_class,retsig=True)
out=[StarDat,"Stellar data from CoRoT spectype & CoRoT lumclass"]
elif corotdf.spectral_type!='' and corotdf.luminosity_class=='':
#Assuming Main Sequence:
out=[StellarNorm(corotdf.spectral_type,['V'],retsig=True),"Stellar data from spectype & assuming main seq."]
#T=np.exp(10,specarr.loc[corotdf.spectral_type,'logT_V'].values[0][0])
#stardat=MS_fit(T)
#return stardat
else:
#No data...
logging.error("No stellar data from CoRoT ExoDat")
return None
else:
if corotdf.luminosity_class=='':
spec = specarr.iloc[np.nanargmin(abs(np.log10(float(corotdf.color_temperature))-specarr.logT_V.values))].name
out=[StellarNorm(spec,['V'],retsig=True),"Stellar data from CoRoT color temperature & assuming main seq."]
#stardat=MS_fit(corotdf.color_temperature.values[0])
#return stardat
elif corotdf.luminosity_class!='':
lum=corotdf.luminosity_class
if lum=='I': lum='Iab'
Tspec='logT_'+lum
spec = specarr.iloc[np.nanargmin(abs(np.log10(float(corotdf.color_temperature))-specarr[Tspec].values))].name
#row=specarr.loc[corotdf.spectral_type]
out=[StellarNorm(spec,corotdf.luminosity_class,retsig=True),"Stellar data from CoRoT color temperature & CoRoT luminosity class"]
if retcomment:
return out
else:
return out[0]
def StellarNorm(spec,lum,retsig=True,n=1000):
#Gets TRMl from spectral type and luminosity class... OR from Temperature and logg
try:
specarr=pd.DataFrame.from_csv('~/ownCloud/PhD/K2/SingleTransits/TypeClassTable.csv')
except:
specarr=pd.DataFrame.from_csv('~/PhD/K2/SingleTransits/TypeClassTable.csv')
if type(spec)!=str:
#Spec is actually a temp...
spec=GetSpecType(spec,specarr)
retspec=True
else:
retspec=False
if type(lum)!=str:
#Lum is actually
try:
lum=GetLumClass(lum,spec,specarr)
except:
lum='V'
if lum=='I':lum='Iab'
#Returns stellar T,R,M and logg, but with either errors (assuming 1-type error in T, and 0.5-class error in lum)
from scipy.interpolate import CloughTocher2DInterpolator as ct2d
#interpolating...
Ms=specarr.columns[:7]
Rs=specarr.columns[7:14]
Ts=specarr.columns[14:21]
gs=specarr.columns[21:]
nl=np.where(np.array(['ZAMS','V','IV','III','II','Ib','Iab','Ia'])==lum)[0]
ns=np.where(specarr.index.values==spec)[0]
xyarr=np.array([(x,y) for x in range(len(specarr.index.values)) for y in range(8)])
Marr=specarr.iloc[:,:8].as_matrix().reshape(-1,1)
Mintrp=ct2d(xyarr[np.where(Marr/Marr==1.0)[0]],Marr[np.where(Marr/Marr==1.0)[0]])
Tarr=specarr.iloc[:,16:24].as_matrix().reshape(-1,1)
Tintrp=ct2d(xyarr[np.where(Tarr/Tarr==1.0)[0]],Tarr[np.where(Tarr/Tarr==1.0)[0]])
Rarr=specarr.iloc[:,8:16].as_matrix().reshape(-1,1)
Rintrp=ct2d(xyarr[np.where(Rarr/Rarr==1.0)[0]],Rarr[np.where(Rarr/Rarr==1.0)[0]])
garr=specarr.iloc[:,24:].as_matrix().reshape(-1,1)
gintrp=ct2d(xyarr[np.where(garr/garr==1.0)[0]],garr[np.where(garr/garr==1.0)[0]])
n=6000 if retsig else 1
#Normal dists around spectral type (+/-1.5 types) and lum class (+/-0.33 classes)
logT=Tintrp(np.random.normal(ns,1.5,n),np.random.normal(nl,0.3,n))
logR=Rintrp(np.random.normal(ns,1.5,n),np.random.normal(nl,0.3,n))
logM=Mintrp(np.random.normal(ns,1.5,n),np.random.normal(nl,0.3,n))
logg=gintrp(np.random.normal(ns,1.5,n),np.random.normal(nl,0.3,n))
if n>1:
if retspec:
return np.power(10,np.percentile(logT[logT/logT==1.0],[16, 50, 84])),\
np.power(10,np.percentile(logR[logR/logR==1.0],[16, 50, 84])),\
np.power(10,np.percentile(logM[logM/logM==1.0],[16, 50, 84])),\
np.percentile(logg[logg/logg==1.0],[16, 50, 84]),spec
else:
return np.power(10,np.percentile(logT[logT/logT==1.0],[16, 50, 84])),\
np.power(10,np.percentile(logR[logR/logR==1.0],[16, 50, 84])),\
np.power(10,np.percentile(logM[logM/logM==1.0],[16, 50, 84])),\
np.percentile(logg[logg/logg==1.0],[16, 50, 84])
else:
if retspec:
return np.power(10,logT[0][0]),np.power(10,logR[0][0]),np.power(10,logM[0][0]),logg[0][0],spec
else:
return np.power(10,logT[0][0]),np.power(10,logR[0][0]),np.power(10,logM[0][0]),logg[0][0]
def GetSpecType(T,specarr=None):
if type(specarr)==type(None):
specarr=pd.DataFrame.from_csv('~/ownCloud/PhD/K2/SingleTransits/TypeClassTable.csv')
return specarr.iloc[np.nanargmin(abs(np.log10(float(T))-specarr.logT_V.values))].name
def GetLumClass(logg,spect,specarr=None):
if type(specarr)==type(None):
specarr=pd.DataFrame.from_csv('~/ownCloud/PhD/K2/SingleTransits/TypeClassTable.csv')
loggarr=specarr.loc[spect,['logg_ZAMS','logg_V','logg_IV','logg_III','logg_II','logg_Ib','logg_Iab','logg_Ia']].values
return ['ZAMS','V','IV','III','II','Ib','Iab','Ia'][np.argmin(abs(logg-loggarr))]
def EstMRT(df):
mks=pd.DataFrame.from_csv('../SpecTypes.csv')
match=mks[(mks['Spec Type']==df.spectral_type.values[0])*(mks['Luminosity Class']==df.luminosity_class.values[0])]
cols=['Mass Mstar/Msun','Luminosity Lstar/Lsun','Radius Rstar/RsunvTemp K','Color Index B-V','Abs Mag','Mv','Bolo Corr BC(Temp)','Bolo Mag Mbol']
df[col] = [match.col for col in cols]
return df
def ExoFopCat(kic,file=''):
import pandas as pd
EPICreqs=pd.DataFrame.from_csv(Namwd+'/Tables/EPICreqs.csv')
if kic in EPICreqs.index.values:
logging.debug("in Exofop csv already")
return list(EPICreqs.loc[kic,['ExoFOP_Teff','ExoFOP_Teff_ERR','ExoFOP_Radi','ExoFOP_Radi_ERR','ExoFOP_Mass','ExoFOP_Mass_ERR']])
else:
#Strips online file for a given epic
import requests
global dump
response=requests.get("https://exofop.ipac.caltech.edu/k2/download_target.php?id="+str(kic))
catfile=response.text
outdat=pd.DataFrame(index={int(kic)})
catsplit=catfile.split('\n')
MAG=-1000;mags=[]
STPS=-1000;stpars=[]
Aliases=[]
for row in catsplit:
row=str(row)
if row=='':
pass
elif row[0:7]=='Proposa':
a=row[13:].replace(' ','')
outdat['K2_Proposal']=a
elif row[0:7]=='Aliases':
a=row[13:].split(',')
for n in range(len(a)):
outdat['ALIAS'+str(n)]=a[n]
elif row.replace(' ','')=='MAGNITUDES:':
MAG=0
elif row.replace(' ','')=='STELLARPARAMETERS:':
MAG=-1000;STPS=0
elif row=='2MASS NEARBY STARS:':
STPS=-1000;MAG=-1000
elif row.replace(' ','')=='SPECTROSCOPY:':
STPS=-1000
outdat['Notes']='fu_spectra'
if MAG>1 and row!='':
a=row[18:50].split()
nom=row[0:17].replace(' ','')
outdat[nom]=float(a[0])
if len(a)>2: outdat[nom+'_ERR']=float(a[1])
if STPS>1 and row!='':
a=row[16:50].split()
nom=str(row[0:16]).translate(None, " (){}[]/")
nom='ExoFOP_'+nom[:4]
if nom in outdat.columns: nom=nom+'_2'
outdat[nom]=float(a[0])
if len(a)>=2: outdat[nom+'_ERR']=float(a[1])
MAG+=1;STPS+=1
EPICreqs.append(outdat)
return list(outdat.loc[outdat.index.values[0],['ExoFOP_Teff','ExoFOP_Teff_ERR','ExoFOP_Radi','ExoFOP_Radi_ERR','ExoFOP_Mass','ExoFOP_Mass_ERR']])
def CutAnomDiff(flux,thresh=4.2):
#Uses differences between points to establish anomalies.
#Only removes single points with differences to both neighbouring points greater than threshold above median difference (ie ~rms)
#Fast: 0.05s for 1 million-point array.
#Must be nan-cut first
diffarr=np.vstack((np.diff(flux[1:]),np.diff(flux[:-1])))
diffarr/=np.median(abs(diffarr[0,:]))
anoms=np.hstack((True,((diffarr[0,:]*diffarr[1,:])>0)+(abs(diffarr[0,:])<thresh)+(abs(diffarr[1,:])<thresh),True))
return anoms
def AnomMedianCut(lc,sigclip=3.2,n=18,iter=5,kind='both'):
#Cuts regions that are [sigclip] times away than the median of the 2*n-long region around each point
#Performs this [iter] times. n must be > largest length of anomalous groups of points
#Can be used for only 'high' points (kind='high'),'low' points (kind='low'), or both (kind='both': DEFAULT)
#Purely in numpy version: about 4 times quicker than a single for loop on the equivalent data.
#creating mask:
mask=np.ones(len(lc), np.bool)
#four iterations...
for p in range(iter):
#creating iteration-specific lc and mask from masters:
inlc=lc[mask]
inmask=np.ones(len(inlc),np.bool)
#stacking data into rows n*2 long (each excluding the central value)
stacks=np.column_stack(([inlc[i:(i-(n*2+1)),1] for i in range(n)+range(n+1,n*2+1)]))
#performing median and std on these datarows and finding where the value is [sigclip]*sigma higher than median
if kind=='both':
wh=n+np.where( abs(inlc[n:(-1-1*n),1]-np.median(stacks,axis=1)) > (sigclip*np.std(stacks,axis=1)) )[0]
elif kind=='high':
wh=n+np.where(inlc[n:(-1-1*n),1]>(np.median(stacks,axis=1)+sigclip*np.std(stacks,axis=1)))[0]
elif kind=='low':
wh=n+np.where(inlc[n:(-1-1*n),1]<(np.median(stacks,axis=1)-sigclip*np.std(stacks,axis=1)))[0]
else:
#kind must be 'both', 'high' or 'low'
raise ValueError(kind)
#Can find + and - anomalies with ( abs(inlc[n:(-1-1*n),1]-np.median(stacks,axis=1)) > (sigclip*np.std(stacks,axis=1)) )
#setting the mask of those anomalous values to False
inmask[wh]=False
#Outgoing mask must unchanged in length. Newly masked points are added to the master mask
mask[mask]=inmask
return mask
def nonan(lc):
return np.logical_not(np.isnan(np.sum(lc,axis=1)))
def K2Centroid(kic,camp,Tcen,Tdur):
'''
#Looking for centroid shifts due to blended eclipsing binary.
#If PDC/hlsff/etc - can use shifts given in lightcurve file
'''
"https://archive.stsci.edu/missions/k2/target_pixel_files/c102/229000000/21000/ktwo229021605-c102_lpd-targ.fits.gz"
tpfname='ktwo'+str(int(kic))+'-c'+str(int(camp))+'_llc.fits'
if not os.path.exists(tpfname):
print('Downloading K2 TPF file from MAST...')
comm='wget -q -nH --cut-dirs=6 -r -l0 -c -N -np -R \'index*\' -erobots=off https://archive.stsci.edu/pub/k2/lightcurves/c'+str(int(camp))+'/'+str(int(kic))[:4]+'00000/'+str(int(kic))[4:6]+'000/'+tpfname
os.system(comm)
#Getting K2 LC
orglc=fits.open(tpfname)
os.system('rm '+tpfname)
cents=np.column_stack((orglc[1].data['TIME'],orglc[1].data['MOM_CENTR1'],orglc[1].data['MOM_CENTR1_ERR'],orglc[1].data['MOM_CENTR2'],orglc[1].data['MOM_CENTR2_ERR']))
cents=cents[nonan(cents)]
intr=abs(cents[:,0]-Tcen)<(0.5*Tdur)
#Median centroid difference for in-transit compared to out-of-transit
meddiff0=np.sqrt((np.median(cents[intr,1])-np.median(cents[~intr,1]))**2+(np.median(cents[intr,3])-np.median(cents[~intr,3]))**2)
#Generating random centroid positions and computing centroid shift for these:
randtcens=np.random.random(100)*(cents[-1,0]-cents[0,0])+cents[0,0]
meddiffs=[]
for tc in randtcens:
intr=abs(cents[:,0]-tc)<(0.5*Tdur)
meddiffs+=[np.sqrt((np.median(cents[intr,1])-np.median(cents[~intr,1]))**2+(np.median(cents[intr,3])-np.median(cents[~intr,3]))**2)]
meddiffs=np.array(meddiffs)
#Comparing transit centroid shift to actual centroid shift.
centshift=meddiff0/np.median(abs(meddiffs[np.logical_not(np.isnan(meddiffs))]))#Centroid shift in sigma (compared to 100 randomly selected transits across the lightcurve)
return centshift
| 83,024 | 44.743802 | 340 | py |
Namaste | Namaste-master/namaste/run.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
:py:mod:`Namaste.py` - Single transit fitting code
-------------------------------------
'''
import numpy as np
import pylab as plt
import scipy.optimize as optimize
from os import sys, path
import datetime
import logging
import pandas as pd
import click
import emcee
import celerite
from .planetlib import *
from .Crossfield_transit import *
from scipy import stats
import scipy.optimize as opt
import pickle
#How best to do this...
#
# make lightcurve a class
# make candidate a class
# make star a class
# make planet a class
# Give candidate a star and planet and lightcurve
# Use the planet to generate the lightcurve model
# Use the star to generate priors
# Give candidate data in the form of a lightcurve - can switch out for CoRoT, Kepler, etc.
class Settings():
'''
The class that contains the model settings
'''
def __init__(self, **kwargs):
self.GP = True # GP on/off
self.nopt = 25 # Number of optimisation steps for each GP and mono before mcmc
self.nsteps = 12500 # Number of MCMC steps
self.npdf = 6000 # Number of samples in the distributions from which to doing calcs.
self.nwalkers = 24 # Number of emcee walkers
self.nthreads = 8 # Number of emcee threads
self.timecut = 6 # Number of Tdurs either side of the transit to be fitted.
self.anomcut = 3.5 # Number of sigma above/below to count as an outlier.
#self.binning = -1 # Days to bin to. -1 dictates no bin
#self.error = False # No error detected
#self.error_comm = '' # Error description
#self.use_previous_samples = False# Using samaples from past run
self.fitsloc = './FitsFiles/' # Storage location to load stuff
self.outfilesloc = './Outputs/' # Storage location to save stuff
self.cadence = 0.0204318 # Cadence. Defaults to K2
self.kernel = 'quasi' # Kernel for use in GPs
self.verbose = True # Print statements or not...
self.mission = 'K2' # Mission
def update(self, **kwargs):
'''
Adding new settings...
'''
self.GP = kwargs.pop('GP', self.GP)
self.nopt = kwargs.pop('nopt', self.nopt)
self.nsteps = kwargs.pop('nsteps', self.nsteps)
self.npdf = kwargs.pop('npdf', self.npdf)
self.nwalkers = kwargs.pop('nwalkers', self.nwalkers)
self.nthreads = kwargs.pop('nthreads', self.nthreads)
self.timecut = kwargs.pop('timecut', self.timecut)
self.anomcut = kwargs.pop('anomcut', self.anomcut)
#self.binning = kwargs.pop('binning', self.binning)
#self.error = kwargs.pop('error', self.binning)
#self.error_comm = kwargs.pop('error_comm', self.binning)
#self.use_previous_samples = kwargs.pop('use_previous_samples', self.binning)
self.fitsloc = kwargs.pop('fitsloc', self.fitsloc)
self.outfilesloc = kwargs.pop('outfilesloc', self.outfilesloc)
self.cadence = kwargs.pop('cadence', self.cadence)
self.kernel = kwargs.pop('kernel', self.kernel)
self.verbose = kwargs.pop('verbose', self.verbose)
self.mission = kwargs.pop('mission', self.mission)
def printall(self):
print(vars(self))
class Star():
def __init__(self, name, settings):
self.objname = name
self.settings = settings
#Initialising lists of monotransits and multi-pl
self.meanmodels=[] #list of mean models to fit.
self.fitdict={} #dictionary of model parameter PDFs to fit
def exofop_dat(self):
#Getting information from exofop...
sdic=ExoFop(int(self.objname))
if 'radius' in sdic.columns:
self.addRad(sdic['radius'],sdic['radius_err'],np.max([sdic['radius']*0.8,sdic['radius_err']]))
else:
raise ValueError("No radius")
if 'teff' in sdic.columns:
self.addTeff(sdic['teff'],sdic['teff_err'],sdic['teff_err'])
else:
raise ValueError("No teff")
if 'mass' in sdic.columns:
self.addMass(sdic['mass'],sdic['mass_err'],sdic['mass_err'])
else:
raise ValueError("No mass")
if 'logg' in sdic.columns:
self.addlogg(sdic['logg'],sdic['logg_err'],sdic['logg_err'])
if 'feh' in sdic.columns:
self.addfeh(sdic['feh'],sdic['feh_err'],sdic['feh_err'])
if 'density' in sdic.columns:
self.addDens(sdic['density'],sdic['density_err'],sdic['density_err'])
else:
self.addDens()
def csvfile_dat(self,file):
#Collecting from CSV file, eg Best_Stellar_Params_nogriz
df=pd.DataFrame.from_csv(file)
row=df.loc[df.epic==int(self.objname)]
csvname=row.index.values[0]
row=row.T.to_dict()[csvname]
self.addRad(row['rad'],row['radep'],row['radem'])
self.addTeff(row['teff'],row['teffep'],row['teffem'])
self.addMass(row['mass'],row['massep'],row['massem'])
self.addlogg(row['logg'],row['loggep'],row['loggem'])
self.addfeh(row['feh'],row['fehep'],row['fehem'])
if not pd.isnull(row['rho']):
self.addDens(row['rho'],row['rhoep'],row['rhoem'])
else:
self.addDens()
#avs avsem avsep dis disem disep epic feh fehem fehep input 2MASS input BV
#input SDSS input_spec logg loggem loggep lum lumem lumep mass massem massep
#n_mod prob rad radem radep rank realspec rho rho_err rhoem rhoep teff teffem teffep
def addTeff(self,val,uerr,derr=None):
self.steff = val
self.steffuerr = uerr
self.steffderr = uerr if type(derr)==type(None) else derr
def addRad(self,val,uerr,derr=None):
self.srad = val
self.sraduerr = uerr
self.sradderr = uerr if type(derr)==type(None) else derr
def addMass(self,val,uerr,derr=None):
self.smass = val
self.smassuerr = uerr
self.smassderr = uerr if type(derr)==type(None) else derr
def addlogg(self,val,uerr,derr=None):
self.slogg = val
self.slogguerr = uerr
self.sloggderr = uerr if type(derr)==type(None) else derr
def addfeh(self,val,uerr,derr=None):
self.sfeh = val
self.sfehuerr = uerr
self.sfehderr = uerr if type(derr)==type(None) else derr
def addDens(self,val=None,uerr=None,derr=None):
if val==None:
val,uerr,derr=CalcDens(self)
else:
#Density defined by others
if val>200:
#Normalising to Solar density:
val/=1410.0;uerr/=1410.0;derr/=1410.0
self.sdens = val
self.sdensuerr = uerr
self.sdensderr = uerr if type(derr)==type(None) else derr
def addLightcurve(self,file):
self.Lcurve=Lightcurve(file,self.objname)
self.mag=self.Lcurve.mag
if self.settings.mission=="kepler" or self.settings.mission=='k2':
self.wn=2.42e-4/np.sqrt(10**((14-self.mag)/2.514)) #2.42e-4 is the White Noise at 14th magnitude for Kepler.
else:
self.wn=np.percentile(abs(np.diff(self.Lcurve.lc[:,1])),40) #Using 40th percentile of the absolute differences.
return self.Lcurve
def EstLimbDark(self):
LDs=getKeplerLDs(self.steffs,logg=self.sloggs,FeH=self.sfeh)
pctns=np.percentile(LDs[0],[15.865525393145707, 50.0, 84.13447460685429])
self.LD1s=LDs[:,0]
self.LD1=pctns[1]
self.LD1uerr=pctns[2]-pctns[1]
self.LD1derr=pctns[1]-pctns[0]
pctns=np.percentile(LDs[1],[15.865525393145707, 50.0, 84.13447460685429])
self.LD2s=LDs[:,1]
self.LD2=pctns[1]
self.LD2uerr=pctns[2]-pctns[1]
self.LD2derr=pctns[1]-pctns[0]
self.initLD()
def PDFs(self):
self.steffs=noneg_GetAssymDist(self.steff,self.steffuerr,self.steffderr,nd=self.settings.npdf)
self.srads =noneg_GetAssymDist(self.srad,self.sraduerr,self.sradderr,nd=self.settings.npdf)
self.smasss=noneg_GetAssymDist(self.smass,self.smassuerr,self.smassderr,nd=self.settings.npdf)
self.sloggs=GetAssymDist(self.slogg,self.slogguerr,self.sloggderr,nd=self.settings.npdf,returndist=True)
self.sdenss=noneg_GetAssymDist(self.sdens,self.sdensuerr,self.sdensderr,nd=self.settings.npdf)
self.EstLimbDark()
def pdflist(self):
if not hasattr(self,'steffs'):
self.PDFs()
if not hasattr(self,'LD1s'):
self.EstLimbDark()
return {'steffs':self.steffs,'srads':self.srads,'smasss':self.smasss,'sloggs':self.sloggs,'sdenss':self.sdenss,\
'LD1s':self.LD1s,'LD2s':self.LD2s}
def addGP(self,vector=None):
if not hasattr(self, 'kern'):
if self.settings.kernel=='Real':
self.kern=celerite.terms.RealTerm(log_a=np.log(np.var(self.Lcurve.lc[:,1])), log_c=-np.log(3.0))+\
celerite.terms.JitterTerm(np.log(self.wn),bounds=dict(log_sigma=(np.log(self.wn)-0.1,np.log(self.wn)+0.1)))
if vector is not None:
self.kern.set_parameter_vector(vector)
self.kern.freeze_parameter('terms[1]:log_sigma') # and freezing white noise
elif self.settings.kernel=='quasi':
self.kern= RotationTerm(np.log(np.var(self.Lcurve.lc[:,1])), np.log(0.25*self.Lcurve.range), np.log(2.5), 0.0,
bounds=dict(
log_amp=(-20.0, -2.0),
log_timescale=(np.log(1.5), np.log(5*self.Lcurve.range)),
log_period=(np.log(1.2), np.log(2*self.Lcurve.range)),
log_factor=(-5.0, 5.0),
)
)+\
celerite.terms.JitterTerm(np.log(self.wn),
bounds=dict(
log_sigma=(np.log(self.wn)-0.1,np.log(self.wn)+0.1)
)
)
if vector is not None:
self.kern.set_parameter_vector(vector)
#self.initgp={'log_amp':,'log_timescale':,'log_period':,'log_factor':,'log_sigma':}
self.kern.freeze_parameter('terms[0]:log_factor') # freezing log factor
self.kern.freeze_parameter('terms[1]:log_sigma') # and freezing white noise
self.initgp={itrm:self.kern.get_parameter(itrm) for itrm in self.kern.get_parameter_names()}
else:
self.initgp={itrm:self.kern.get_parameter(itrm) for itrm in self.kern.get_parameter_names()}
def Optimize_GP(self):
#Optimizing initial GP parameters, depending on GP supplied...
'''
#This optimizes the gaussian process on out-of-transit data. This is then held with a gaussian prior during modelling
'''
import scipy.optimize as op
#Cutting transits from lc
self.Lcurve.calc_mask(self.meanmodels)
lc_trn=self.Lcurve.lc[self.Lcurve.lcmask]
lc_trn[:,1]/=np.nanmedian(lc_trn[:,1])#This half may be different in median from the full lc, so adjusting for this...
if not hasattr(self,'gp'):
self.addGP()
self.kern.thaw_all_parameters()
gp_notr=celerite.GP(kernel=self.kern,mean=1.0,fit_mean=True)
gp_notr.compute(lc_trn[:,0],lc_trn[:,2])
#Initial results:
init_res=op.minimize(neg_log_like, list(gp_notr.get_parameter_vector()), args=(lc_trn[:,1],gp_notr), method="L-BFGS-B")#jac=grad_neg_log_like
fails=0
if self.settings.kernel=='quasi':
suc_res=np.zeros(7)
# Run the optimization routine for a grid of size self.settings.nopt
#log_amp, log_timescale, log_period, log_factor, log_sigma, mean = params
iterparams= np.column_stack((np.random.normal(gp_notr.kernel.get_parameter_vector()[0],3.0,self.settings.nopt),
np.random.uniform(1.2,np.log(0.75*self.Lcurve.range),self.settings.nopt),
np.random.uniform(np.log(6*self.settings.cadence),np.log(0.75*self.Lcurve.range),self.settings.nopt),
np.tile(0.0,self.settings.nopt)))
elif self.settings.kernel=='Real':
suc_res=np.zeros(4)
#log_a, log_c = params
iterparams=np.column_stack((np.random.normal(gp_notr.kernel.get_parameter_vector()[0],np.sqrt(abs(gp_notr.kernel.get_parameter_vector()[0])),self.settings.nopt),
np.random.normal(gp_notr.kernel.get_parameter_vector()[1],np.sqrt(abs(gp_notr.kernel.get_parameter_vector()[1])),self.settings.nopt)))
for n_p in np.arange(self.settings.nopt):
vect=np.hstack((iterparams[n_p],np.log(self.wn),1.0))
#gp_notr.kernel.set_parameter_vector(vect)
try:
result = op.minimize(neg_log_like, vect, args=(lc_trn[:,1], gp_notr), method="L-BFGS-B")# jac=grad_nll,")
if result.success:
#print("success,",result.fun)
suc_res=np.vstack((suc_res,np.hstack((result.x,result.fun))))
else:
fails+=1
except:
#print("fail,",vect)
fails+=1
print(suc_res) if self.settings.verbose else 0
print(str(fails)+" failed attempts out of "+str(self.settings.nopt)) if self.settings.verbose else 0
if len(np.shape(suc_res))==1:
raise ValueError("No successful GP minimizations")
else:
suc_res=suc_res[1:,:]
bestres=suc_res[np.argmin(suc_res[:,-1])]
gp_notr.set_parameter_vector(bestres[:-1])
self.optimised_gp=gp_notr
wn_factor = bestres[4]-np.log(self.wn)
self.optgp={itrm:gp_notr.get_parameter(itrm) for itrm in gp_notr.get_parameter_names()}
# Update the kernel and print the final log-likelihood.
for itrm in gp_notr.kernel.get_parameter_names()[:-1]:
self.kern.set_parameter(itrm,gp_notr.kernel.get_parameter(itrm))
if self.settings.kernel=='quasi':
self.kern.freeze_parameter('terms[0]:log_factor') # re-freezing log factor
self.kern.freeze_parameter('terms[1]:log_sigma') # and re-freezing white noise
#Adding
self.fitdict.update({'kernel:'+nm:np.random.normal(gp_notr.get_parameter('kernel:'+nm),1.5,self.settings.nwalkers) for nm in self.kern.get_parameter_names()})
print("white noise changed by a factor of "+str(np.exp(wn_factor))[:4]) if self.settings.verbose else 0
print("GP improved from ",init_res.fun," to ",bestres[-1]) if self.settings.verbose else 0
'''return bestres[:-2] #mean_shift... is this indicative of the whole lightcurve or just this half of it?'''
def AddMonotransit(self, tcen, tdur, depth, b=0.41,replace=True):
if not hasattr(self,'steffs'):
self.PDFs()
#Adding monotransit classes to the star class... Up to four possible.
if not hasattr(self,'mono1') or replace:
#self.LD1s, self.LD2s, self.sdenss,self.Lcurve.lc,
self.mono1 = Monotransit(tcen, tdur, depth, self.settings, name=self.objname+'.1')
self.mono1.calcmaxvel(self.Lcurve.lc,self.sdenss)
self.mono1.Optimize_mono(self.Lcurve.flatten(),self.LDprior.copy())
self.mono1.SaveInput(self.pdflist())
self.meanmodels+=[self.mono1]
'''
while a<=5 and len(self.meanmodels)==initlenmonos:
if not hasattr(self,'mono'+str(a)) or replace:
setattr(self,'mono'+str(a)) = Monotransit(tcen, tdur, depth, self.settings, self.LD1s, self.LD2s, self.denss,self.lc, name=self.objname+'.'+str(a), b=b)
exec("self.mono"+str(a)+".Optimize_mono(Lcurve.flaten())")
exec("self.mono"+str(a)+".calcmaxvel(self.Lcurve.lc,self.sdenss)")
exec("self.meanmodels+=[self.mono"+str(a)+"]")
a+=1
'''
def AddNormalPlanet(self, tcen, tdur, depth, Period, b=0.41,replace=False):
if not hasattr(self,'steffs'):
self.PDFs()
#Adding transiting planet classes to the star class using dfm's "transit"... Up to four possible.
if not hasattr(self,'norm1') or replace:
self.norm1 = Multtransit(tcen, tdur, depth, self.settings, name=self.objname+'.5', b=b)
self.meanmodels+=[self.norm1]
'''
while a<=5 and len(self.meanmodels)==initlenmonos:
if not hasattr(self,'mono'+str(a)) or replace:
setattr(self,'mono'+str(a)) = Monotransit(tcen, tdur, depth, self.settings, self.LD1s, self.LD2s, self.denss,self.lc, name=self.objname+'.'+str(a), b=b)
exec("self.mono"+str(a)+".Optimize_mono(Lcurve.flaten())")
exec("self.mono"+str(a)+".calcmaxvel(self.Lcurve.lc,self.sdenss)")
exec("self.meanmodels+=[self.mono"+str(a)+"]")
a+=1
'''
def initLD(self):
if not hasattr(self,'steffs'):
self.PDFs()
#Getting LD parameters for transit modelling:
self.LDprior={'LD1':[0,1.0,'gaussian',np.median(self.LD1s),np.std(self.LD1s)],
'LD2':[0,1.0,'gaussian',np.median(self.LD2s),np.std(self.LD2s)]}
def BuildMeanModel(self):
#for model in self.meanmodels: #<<<TBD
self.meanmodel_comb=MonotransitModel(tcen=self.mono1.tcen,
b=self.mono1.b,
vel=self.mono1.vel,
RpRs=self.mono1.RpRs,
LD1=np.median(self.LD1s),
LD2=np.median(self.LD2s))
def BuildMeanPriors(self):
#Building mean model priors
if not hasattr(self, 'LDprior'):
self.initLD()
self.meanmodel_priors=self.mono1.priors.copy()
self.meanmodel_priors.update({'mean:'+ldp:self.LDprior[ldp] for ldp in self.LDprior})
def BuildAllPriors(self,keylist=None):
#Building priors from both GP and mean model and ordering by
if not hasattr(self, 'meanmodel_priors'):
self.BuildMeanPriors()
self.priors=self.meanmodel_priors.copy()#{key:self.meanmodel_priors[key] for key in self.meanmodel_priors.keys()}
self.priors.update({'kernel:'+self.kern.get_parameter_names()[keyn]:[self.kern.get_parameter_bounds()[keyn][0],
self.kern.get_parameter_bounds()[keyn][1]]
for keyn in range(len(self.kern.get_parameter_names()))
})
self.priors['kernel:terms[0]:log_amp']=self.priors['kernel:terms[0]:log_amp']+['evans',0.25*len(self.Lcurve.lc[:,0])]
print(self.priors)
if keylist is not None:
#Sorting to match parameter vector:
newprior={key:self.priors[key] for key in keylist}
#print(str(len(keylist))+" keys in vector leading to "+str(len(newprior))+" new keys in priors, from "+str(len(self.priors))+" initially") if self.settings.verbose else 0
self.priors=newprior
print(self.priors)
def RunModel(self):
self.BuildMeanPriors()
self.BuildMeanModel()
self.gp=celerite.GP(kernel=self.kern,mean=self.meanmodel_comb,fit_mean=True)
self.BuildAllPriors(self.gp.get_parameter_names())
#Returning monotransit model from information.
chx=np.random.choice(self.settings.npdf,self.settings.nwalkers,replace=False)
self.fitdict.update({'mean:'+nm:getattr(self.mono1,nm+'s')[chx] for nm in ['tcen','b','vel','RpRs']})
self.fitdict.update({'mean:'+nm:getattr(self,nm+'s')[chx] for nm in ['LD1','LD2']})
#Removing medians:
for row in self.fitdict:
self.fitdict[row][np.isnan(self.fitdict[row])]=np.nanmedian(np.isnan(self.fitdict[row]))
dists=[self.fitdict[cname] for cname in self.gp.get_parameter_names()]
self.init_mcmc_params=np.column_stack(dists)
print(np.shape(self.init_mcmc_params))
#[,:])
mask=abs(self.Lcurve.lc[:,0]-self.gp.get_parameter('mean:tcen'))<2.75
PlotModel(self.Lcurve.lc[mask,:], self.gp, np.median(self.init_mcmc_params,axis=0), fname=self.settings.outfilesloc+self.objname+'_initfit.png')
#dists=[np.random.normal(self.gp.get_parameter(nm),abs(self.gp.get_parameter(nm))**0.25,len(chx)) for nm in ['kernel:terms[0]:log_amp', 'kernel:terms[0]:log_timescale', 'kernel:terms[0]:log_period']]+\
# [self.tcens[chx],self.bs[chx],self.vels[~np.isnan(self.vels)][chx],self.RpRss[chx],self.LD1s[chx],self.LD2s[chx]]
#'kernel:terms[0]:log_factor', 'kernel:terms[1]:log_sigma' <- frozen and not used
#print(len(pos[0,:]))
#[np.array(list(initparams.values())) *(1+ 1.5e-4*np.random.normal()) for i in range(nwalkers)]
print("EMCEE HAPPENING. INIT DISTS:")
print(self.init_mcmc_params[0,:])
print(self.gp.get_parameter_names())
print(self.priors.keys())
#print(' , '.join( [str(list(self.priors.keys())[nk]) [-8:]+' - '+str(abs(self.priors[list(self.priors.keys())[nk]]-self.init_mcmc_params[nk]))[:5] for nk in range(len(self.priors.keys()))]) )
print(' \n '.join([str(list(self.priors.keys())[nk])+' - '+str(self.priors[list(self.priors.keys())[nk]][0])+" > "+str(np.median(self.init_mcmc_params[nk]))+\
" < "+str(self.priors[list(self.priors.keys())[nk]][1]) for nk in range(len(self.priors.keys()))]\
)) if self.settings.verbose else 0
self.sampler = emcee.EnsembleSampler(self.settings.nwalkers, len(self.gp.get_parameter_vector()), MonoLogProb, args=(self.Lcurve.lc,self.priors,self.gp), threads=self.settings.nthreads)
self.sampler.run_mcmc(self.init_mcmc_params, 1, rstate0=np.random.get_state())
self.sampler.run_mcmc(self.init_mcmc_params, self.settings.nsteps, rstate0=np.random.get_state())
#Trimming samples:
ncut=np.min([int(self.settings.nsteps*0.25),3000])
lnprobs=self.sampler.lnprobability[:,ncut:]#.reshape(-1)
prcnt=np.percentile(lnprobs,[50,95],axis=1)
#"Failed" walkers are where the 97th percentile is below the median of the rest
good_wlkrs=(prcnt[1]>np.median(prcnt[0]))
self.sampleheaders=self.gp.get_parameter_names()+['logprob']
self.samples = self.sampler.chain[good_wlkrs, ncut:, :].reshape((-1, len(self.gp.get_parameter_vector())))
self.samples = np.column_stack((self.samples,self.sampler.lnprobability[good_wlkrs,ncut:].reshape(-1)))
#Making impact parameter always positive:
self.samples[:,1]=abs(self.amples[:,1])
self.SaveMCMC()
def SaveMCMC(self):
np.save(self.settings.outfilesloc+self.objname+'_MCMCsamples',self.samples)
def MonoFinalPars(self,model=None):
if model is None and hasattr(self,'mono1'):
model=self.mono1
#Taking random Nsamples from samples to put through calculations
#Need to form assymetric gaussians of Star Dat parameters if not equal
#Rstardist2=np.hstack((np.sort(Rstardist[:, 0])[0:int(nsamp/2)], np.sort(Rstardist[:, 1])[int(nsamp/2):] ))
modelmeanvals=[col.find('mean:')!=-1 for col in self.sampleheaders]
model.gen_PDFs({modelmeanvals[nmmv].split(":")[-1]+'s':self.samples[:,modelmeanvals][:,nmmv] for nmmv in modelmeanvals})
rn=np.random.choice(len(self.samples[:,0]),self.settings.npdf,replace=False)
#for model in meanmodels:
setattr(model,Rps,(self.samples[rn,self.sampleheaders=='mean:RpRs']*695500000*self.Rss)/6.371e6)#inearths
setattr(model,'Prob_pl',len(model.Rps[model.Rps<(1.5*11.2)])/len(model.Rps))
aest,Pest=VelToOrbit(self.samples[rn,self.sampleheaders=='mean:vel'], self.sdenss, self.Mss)
setattr(model,smas,aest)
setattr(model,Ps,Pest)
setattr(model,Mps,PlanetRtoM(model.Rps))
setattr(model,Krvs,((2.*np.pi*6.67e-11)/(model.Ps*86400))**(1./3.)*(model.Mps*5.96e24/((1.96e30*self.Mss)**(2./3.))))
#sigs=np.array([2.2750131948178987, , 97.7249868051821])
sigs=[15.865525393145707, 50.0, 84.13447460685429]
for val in ['Rps','smas','Ps','Mps','Krvs']:
percnts=np.percentile(np.array(getattr(model,val)), sigs)
setattr(model,val[:-1],percnts[1])
setattr(model,val[:-1]+'uerr',(percnts[2]-percnts[1]))
setattr(model,val[:-1]+'derr',(percnts[1]-percnts[0]))
def PlotMCMC(usecols=None):
import corner
newnames={'kernel:terms[0]:log_amp':'$\log{a}$',
'kernel:terms[0]:log_timescale':'$\log{\tau}$',
'kernel:terms[0]:log_period':'$\log{P}$',
'mean:tcen':'$t_{\rm cen}$',
'mean:b':'$b$',
'mean:vel':'$v\'$',
'mean:RpRs':'$R_p/R_s$',
'mean:LD1':'LD$_1$',
'mean:LD2':'LD$_2$'}
if usecols is None:
#Plotting corner with all parameter names
usecols=self.gp.get_parameter_names()
plt.figure(1)
Npars=len(samples[0]-1)
tobeplotted=np.in1d(gp.get_parameter_names(),usecols)
#Clipping extreme values (top.bottom 0.1 percentiles)
toclip=np.array([(np.percentile(self.samples[:,t],99.9)>self.samples[:,t]) // (self.samples[:,t]>np.percentile(self.samples[:,t],0.1)) for t in range(Npars)[tobeplotted]]).all(axis=0)
clipsamples=self.samples[toclip]
#Earmarking the difference between GP and non
labs = [newnames[key] for key in gp.get_parameter_names() if key in usecols]
#This plots the corner:
fig = corner.corner(clipsamples[:,tobeplotted], labels=labs, quantiles=[0.16, 0.5, 0.84], plot_datapoints=False,range=np.tile(0.985,Npars))
#Making sure the lightcurve plot doesnt overstep the corner
ndim=np.sum(tobeplotted)
rows=(ndim-1)/2
cols=(ndim-1)/2
#Printing Kepler name on plot
plt.subplot(ndim,ndim,ndim+3).axis('off')
plt.title(str(self.objname), fontsize=22)
#This plots the model on the same plot as the corner
ax = plt.subplot2grid((ndim,ndim), (0, ndim-cols), rowspan=rows-1-int(GP), colspan=cols)
modelfits=PlotModel(self.Lcurve.lc, self.gp, np.nanmedian(self.samples,axis=0)) #(lc, samples, scale=1.0, GP=GP)
#If we do a Gaussian Process fit, plotting both the transit-subtractedGP model and the residuals
ax=plt.subplot2grid((ndim,ndim), (rows-2, ndim-cols), rowspan=1, colspan=cols)
_=PlotModel(self.Lcurve.lc, self.gp, np.nanmedian(self.samples,axis=0), prevmodels=modelfits, subGP=True)
#plotting residuals beneath:
ax = plt.subplot2grid((ndim,ndim), (rows-1, ndim-cols), rowspan=1, colspan=cols)
_=PlotModel(self.Lcurve.lc, self.gp, np.nanmedian(self.samples,axis=0), prevmodels=modelfits, residuals=True)
#Adding text values to MCMC pdf
#Plotting text wrt to residuals plot...
xlims=ax.get_xlim()
x0=(xlims[0]+0.5*(xlims[1]-xlims[0])) #Left of box in x
xwid=0.5*(xlims[1]-xlims[0]) #Total width of ybox
ylims=ax.get_ylim()
y1=(ylims[0]-0.5*(ylims[1]-ylims[0])) #Top of y box
yheight=-2.5*(ylims[1]-ylims[0]) #Total height of ybox
from matplotlib import rc;rc('text', usetex=True)
#matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]
matplotlib.rcParams['text.latex.preamble'] = [r'\boldmath']#Needed for latex commands here:
plt.text(x0+0.14*xwid,y1,"EPIC"+str(self.objname),fontsize=20)
n_textpos=0
txt=["EPIC"+str(self.objname)]
sigs=[2.2750131948178987, 15.865525393145707, 50.0, 84.13447460685429, 97.7249868051821]
for lab in labs:
xloc=x0+0.05*xwid
yloc=y1+0.02*yheight+(0.05*yheight*(n+1))
if lab=='$t_{\rm cen}$':#Need larger float size for Tcen...
txt+=[r"\textbf{"+lab+":} "+('%s' % float('%.8g' % (np.median(self.samples[:,n]))))+" +"+('%s' % float('%.2g' % (np.percentile(self.samples[:,n_textpos],sigs[3])-np.median(self.samples[:,n_textpos]))))+" -"+\
('%s' % float('%.2g' % (np.median(self.samples[:,n_textpos])-np.percentile(self.samples[:,n_textpos],sigs[1]))))]
plt.text(xloc,yloc,txt[-1])
else:
txt+=[r"\textbf{"+lab+":} "+('%s' % float('%.3g' % (np.median(self.samples[:,n]))))+" +"+('%s' % float('%.2g' % (np.percentile(self.samples[:,n_textpos],sigs[3])-np.median(self.samples[:,n_textpos]))))+" -"+\
('%s' % float('%.2g' % (np.median(self.samples[:,n_textpos])-np.percentile(self.samples[:,n_textpos],sigs[1]))))]
plt.text(xloc,yloc,txt[-1])
n_textpos+=1
info={'Rps':'$R_p (R_{\oplus})$','Ps':'Per (d)','smas':'A (au)','Mps':'$M_p (M_{\oplus})$','Krvs':'K$_{\rm rv}$(ms$^{-1}$)','Prob_pl':'ProbPl ($\%$)',\
'steffs':'Teff (K)','srads':'Rs ($R_{\odot}$)','smasss':'Ms ($M_{\odot}$)','sloggs':'logg','sdenss':'$\\rho_s (\\rho_{\odot})$'}
pdfs=self.pdflist()
for ival in pdfs:
if ival[:2]!='LD':
xloc=x0+0.05*xwid
yloc=y1+0.02*yheight+(0.05*yheight*(n_textpos+2))
vals=np.percentile(pdfs[ival],sigs)
txt+=[(r"\textbf{%s:} " % info[ival])+('%s' % float('%.3g' % vals[2]))+" +"+\
('%s' % float('%.2g' % (vals[3]-vals[2])))+" -"+('%s' % float('%.2g' % (vals[2]-vals[1])))]
plt.text(xloc,yloc,txt[-1])
n_textpos+=1
self.MonoFinalPars()
for ival in ['Rps','smas','Ps','Mps','Krvs']:
xloc=x0+0.05*xwid
yloc=y1+0.02*yheight+(0.05*yheight*(n_textpos+2))
vals=np.percentile(getattr(self.mono1,ival),sigs)
txt+=[(r"\textbf{%s:} " % info[ival])+('%s' % float('%.3g' % vals[2]))+" +"+\
('%s' % float('%.2g' % (vals[3]-vals[2])))+" -"+('%s' % float('%.2g' % (vals[2]-vals[1])))]
plt.text(xloc,yloc,txt[-1])
n_textpos+=1
xloc=x0+0.05*xwid
yloc=y1+0.02*yheight+(0.05*yheight*(2+n_textpos+1))
txt+=[(r"\textbf{%s:} " % info['Prob_pl'])+('%s' % float('%.3g' % getattr(self.mono1,'Prob_pl')))]
plt.text(xloc,yloc,txt[-1])
with open(self.settings.outfilesloc+'latextable.tex','ra') as latextable:
latextable.write(' & '.join(txt)+'/n')
#Saving as pdf. Will save up to 3 unique files.
fname='';n=0
while fname=='':
if os.path.exists(self.settings.outfilesloc+'Corner_'+str(self.objname)+'_'+str(int(n))+'.pdf'):
n+=1
else:
fname=self.settings.outfilesloc+'/Corner_'+str(EPIC)+'_'+str(int(n))+'.pdf'
plt.savefig(fname,Transparent=True,dpi=300)
plt.savefig(fname.replace('pdf','png'),Transparent=True,dpi=300)
class Monotransit():
#Monotransit detection to analyse
def __init__(self, tcen, tdur, depth, settings, name, b=0.4, RpRs=None, vel=None,\
tcenuerr=None,tduruerr=None,depthuerr=None,buerr=None,RpRsuerr=None, veluerr=None,\
tcenderr=None,tdurderr=None,depthderr=None,bderr=None,RpRsderr=None,velderr=None):
self.settings=settings
self.mononame = name
self.starname = name.split('.')[0]
self.pdfs = {}
self.update_pars(tcen, tdur, depth, b=b, RpRs=RpRs, vel=vel,
tcenuerr=tcenuerr,tduruerr=tduruerr,depthuerr=depthuerr,buerr=buerr, RpRsuerr=RpRsuerr,veluerr=veluerr,
tcenderr=tcenderr,tdurderr=tdurderr,depthderr=depthderr,bderr=bderr,RpRsderr=RpRsderr, velderr=velderr)
self.gen_PDFs()
'''
def addStarDat(self,pdflist):
self.LD1s=pdflist['LD1s']
self.LD2s=pdflist['LD2s']
self.srads=pdflist['srads']
self.sdenss=pdflist['sdenss']
self.smasss=pdflist['smasss']
self.steffs=pdflist['steffs']
self.pdfs.update({'LD1s':self.LD1s,'LD2s':self.LD2s,'srads':self.srads,'sdenss':self.sdenss,'smasss':self.smasss,'steffs':self.steffs})
'''
def update_pars(self, tcen=None, tdur=None, depth=None, b=0.4, RpRs=None, vel=None, tcenuerr=None,tduruerr=None,depthuerr=None,buerr=None,RpRsuerr=None, tcenderr=None,tdurderr=None,depthderr=None,bderr=None,RpRsderr=None,veluerr=None,velderr=None):
if tcen is not None:
self.tcen = float(tcen) # detected transit centre
self.tcenuerr = 0.15*tdur if type(tcenuerr)==type(None) else tcenuerr # estimated transit centre errors (default = 0.1*dur)
self.tcenderr = 0.15*tdur if type(tcenderr)==type(None) else tcenderr # estimated transit centre errors (default = 0.1*dur)
if tdur is not None:
self.tdur = float(tdur) # detected transit duration
self.tduruerr = 0.33*tdur if type(tcenuerr)==type(None) else tcenuerr # estimated transit duration errors (default = 0.2*dur)
self.tdurderr = 0.33*tdur if type(tcenuerr)==type(None) else tcenuerr # estimated transit duration errors (default = 0.2*dur)
if depth is not None:
self.depth = float(depth) # detected transit depth
self.depthuerr = 0.33*depth if type(tcenuerr)==type(None) else tcenuerr # estimated transit depth errors (default = 0.1*depth)
self.depthderr = 0.33*depth if type(tcenuerr)==type(None) else tcenuerr # estimated transit depth errors (default = 0.1*depth)
self.b = 0.5 if type(b)==type(None) else b # estimated impact parameter (default = 0.5)
self.buerr = 0.5 if type(buerr)==type(None) else buerr # estimated impact parameter errors (default = 0.5)
self.bderr = 0.5 if type(bderr)==type(None) else bderr # estimated impact parameter errors (default = 0.5)
self.RpRs = self.depth**0.5 if type(RpRs)==type(None) else RpRs # Ratio of planet to star radius
self.RpRsuerr = 0.5*self.RpRs if type(RpRsuerr)==type(None) else RpRsuerr # Ratio of planet to star radius errors (default = 25%)
self.RpRsderr = 0.5*self.RpRs if type(RpRsderr)==type(None) else RpRsderr # Ratio of planet to star radius errors (default = 25%)
#self.vel = CalcVel() # Velocity of planet relative to stellar radius
if vel is not None:
self.vel = vel # Velocity scaled to stellar radius
elif not hasattr(self,'vel'):
self.vel = None # Velocity scaled to stellar radius
def gen_PDFs(self,paramdict=None):
#Turns params into PDFs
if paramdict is None:
self.tcens=GetAssymDist(self.tcen,self.tcenuerr,self.tcenderr,nd=self.settings.npdf,returndist=True)
#self.depths=GetAssymDist(self.depth,self.depthuerr,self.depthderr,nd=self.settings.npdf,returndist=True)
self.bs=abs(GetAssymDist(self.b,self.buerr,self.bderr,nd=self.settings.npdf,returndist=True))
self.RpRss=GetAssymDist(self.RpRs,self.RpRsuerr,self.RpRsderr,nd=self.settings.npdf,returndist=True)
#Velocity tends to get "Nan"-y, so looping to avoid that:
nanvels=np.tile(True,self.settings.npdf)
v=np.zeros(self.settings.npdf)
while np.sum(nanvels)>self.settings.npdf*0.002:
v[nanvels]=CalcVel(np.random.normal(self.tdur,self.tdur*0.15,nanvels.sum()), self.bs[np.random.choice(self.settings.npdf,np.sum(nanvels))], self.RpRss[np.random.choice(self.settings.npdf,np.sum(nanvels))])
nanvels=(np.isnan(v))*(v<0.0)*(v>100.0)
self.vels=v
prcnts=np.diff(np.percentile(self.vels[~np.isnan(self.vels)],[15.865525393145707, 50.0, 84.13447460685429]))
self.veluerr=prcnts[1]
self.velderr=prcnts[0]
if self.vel is not None and ~np.isnan(self.vel):
#Velocity pre-defined. Distribution is not, however, so we'll use the scaled distribution of the "derived" velocity dist to give the vel errors
velrat=self.vel/np.nanmedian(self.vels)
self.vels*=velrat
self.veluerr*=velrat
self.velderr*=velrat
else:
self.vel=np.nanmedian(self.vels)
else:
#included dictionary of new "samples"
sigs=[15.865525393145707, 50.0, 84.13447460685429]
for colname in ['tcens','bs','vels','RpRss']:
setattr(self,colname,paramdict[colname])
percnts=np.percentile(np.array(getattr(model,colname)), sigs)
setattr(self,colname[:-1],percnts[1])
setattr(self,colname[:-1]+'uerr',percnts[2]-percnts[1])
setattr(self,colname[:-1]+'derr',percnts[1]-percnts[0])
self.pdfs.update({'tcens':self.tcens,'bs':self.bs,'RpRss':self.RpRss,'vels':self.vels})
#if StarPDFs is not None:
# self.pdflist.update(StarPDFs)
def calcmaxvel(self,lc,sdenss):
#Estimate maximum velocity given lightcurve duration without transit.
self.calcminp(lc)
maxvels=np.array([((18226*rho)/self.minp)**(1/3.0) for rho in abs(sdenss)])
prcnts=np.percentile(maxvels,[15.865525393145707, 50.0, 84.13447460685429])
self.maxvelderr=prcnts[1]-prcnts[0]
self.maxvel=prcnts[1]
self.maxveluerr=prcnts[2]-prcnts[1]
def calcminp(self,lc):
#finding tdur-wide jumps in folded LC
dur_jumps=np.where(np.diff(abs(lc[:,0]-self.tcen))>self.tdur)[0]
if len(dur_jumps)==0:
#No tdur-wide jumps until end of lc - using the maximum difference to a point in the lc
self.minp=np.max(abs(lc[:,0]-self.tcen))+self.tdur*0.33
else:
#Taking the first Tdur-wide jump in the folded lightcurve where a transit could be hiding.
self.minp=abs(lc[:,0]-self.tcen)[dur_jumps[0]]+self.tdur*0.33
'''
def CalcOrbit(self,denss):
#Calculating orbital information
#VelToOrbit(Vel, Rs, Ms, ecc=0, omega=0):
SMA,P=Vel2Per(denss,self.vels)
self.SMAs=SMA
self.PS=P
def update(self, **kwargs):
#Modify detection parameters...
self.tcen = kwargs.pop('tcen', self.tcen) # detected transit centre
self.tdur = kwargs.pop('tdur', self.tdur) # detected transit duration
self.depth = kwargs.pop('dep', self.depth) # detected transit depth
self.b = kwargs.pop('b', self.b) # estimated impact parameter (default = 0.4)
self.RpRs = kwargs.pop('RpRs', self.RpRs) # Ratio of planet to star radius
self.vel = kwargs.pop('vel', self.vel) # Velocity of planet relative to stellar radius
def FitParams(self,star,info):
#Returns params array needed for fitting
if info.GP:
return np.array([self.tcen,self.b,self.vel,self.RpRs])
else:
return np.array([self.tcen,self.b,self.vel,self.RpRs])
def InitialiseGP(self,settings,star,Lcurve):
import george
self.gp, res, self.lnlikfit = TrainGP(Lcurve.lc,self.tcen,star.wn)
self.newmean,self.newwn,self.a,self.tau=res
def FitPriors(self,star,settings):
#Returns priros array needed for fitting
if settings.GP:
if not self.hasattr('tau'):
self.InitialiseGP()
return np.array([[self.tcen,self.tcen,self.tcen,self.tcen],
[-1.2,1.2,0,0],
[0.0,100.0,self.vmax,self.vmaxerr],
[0.0,0.3,0,0],
[0.0,1.0,star.LD1,np.average(star.LD1uerr,star.LD1derr)],
[0.0,1.0,star.LD2,np.average(star.LD2uerr,star.LD2derr)],
[np.log(star.wn)-1.5,np.log(star.wn)+1.5,np.log(star.wn),0.3],
[self.tau-10,self.tau+10,self.tau,np.sqrt(np.abs(self.tau))],
[self.a-10,self.a+10,self.a,np.sqrt(np.abs(self.a))]])
else:
return np.array([[self.tcen,self.tcen,self.tcen,self.tcen],
[-1.2,1.2,0,0],
[0.0,100.0,self.vmax,self.vmaxerr],
[0.0,0.3,0,0],
[0.0,1.0,star.LD1,np.average(star.LD1uerr,star.LD1derr)],
[0.0,1.0,star.LD2,np.average(star.LD2uerr,star.LD2derr)]]
'''
def Optimize_mono(self,flatlc,LDprior,nopt=20):
if not hasattr(self,'priors'):
self.monoPriors()
#Cutting to short area around transit:
flatlc=flatlc[abs(flatlc[:,0]-self.tcen)<5*self.tdur]
#Optimizing initial transit parameters
opt_monomodel=MonotransitModel(tcen=self.tcen,
b=self.b,
vel=self.vel,
RpRs=self.RpRs,
LD1=LDprior['LD1'][3],
LD2=LDprior['LD2'][3])
print(self.priors)
temp_priors=self.priors.copy()
temp_priors['mean:LD1'] = LDprior['LD1']
temp_priors['mean:LD2'] = LDprior['LD2']
print("monopriors:",temp_priors) if self.settings.verbose else 0
init_neglogprob=MonoOnlyNegLogProb(opt_monomodel.get_parameter_vector(),flatlc,temp_priors,opt_monomodel)
print("nll init",init_neglogprob) if self.settings.verbose else 0
suc_res=np.zeros(7)
LD1s=np.random.normal(LDprior['LD1'][3],LDprior['LD1'][4],self.settings.npdf)
LD2s=np.random.normal(LDprior['LD2'][3],LDprior['LD2'][4],self.settings.npdf)
#Running multiple optimizations using rough grid of important model paramsself.
for n_par in np.random.choice(self.settings.npdf,nopt,replace=False):
initpars=np.array([self.tcens[n_par],self.bs[n_par],self.vels[n_par],self.RpRss[n_par],LD1s[n_par],LD2s[n_par]])
result = opt.minimize(MonoOnlyNegLogProb, initpars, args=(flatlc, temp_priors, opt_monomodel), method="L-BFGS-B")
if result.success:
suc_res=np.vstack((suc_res,np.hstack((result.x,result.fun))))
if len(np.shape(suc_res))==1:
raise ValueError("No successful Monotransit minimizations")
else:
#Ordering successful optimizations by neglogprob...
suc_res=suc_res[1:,:]
print("All_Results:",suc_res) if self.settings.verbose else 0
suc_res=suc_res[~np.isnan(suc_res[:,-1]),:]
bestres=suc_res[np.argmin(suc_res[:,-1])]
self.bestres=bestres
print("Best_Result:",bestres) if self.settings.verbose else 0
#tcen, tdur, depth, b=0.4, RpRs=None, vel=None
self.update_pars(bestres[0], CalcTdur(bestres[2], bestres[1], bestres[3]), bestres[3]**2, b=bestres[1], RpRs=bestres[3],vel=bestres[2])
print("initial fit nll: ",init_neglogprob," to new fit nll: ",bestres[-1]) if self.settings.verbose else 0
#for nn,name in enumerate(['mean:tcen', 'mean:b', 'mean:vel', 'mean:RpRs', 'mean:LD1', 'mean:LD2']):
# self.gp.set_parameter(name,bestres[nn])
PlotBestMono(flatlc, opt_monomodel, bestres[:-1], fname=self.settings.outfilesloc+self.mononame+'_init_monoonly_fit.png')
def monoPriors(self,name='mean'):
self.priors={}
self.priors.update({name+':tcen':[self.tcen-self.tdur*0.3,self.tcen+self.tdur*0.3],
name+':b':[0.0,1.25],
name+':vel':[0,self.maxvel+5*self.maxveluerr,'normlim',self.maxvel,self.maxveluerr],
name+':RpRs':[0.02,0.25]
})
return self.priors
'''
def RunModel(self,lc,gp):
self.modelPriors()
#Returning monotransit model from information.
sampler = emcee.EnsembleSampler(self.settings.nwalkers, len(gp.get_parameter_vector()), MonoLogProb, args=(lc,self.priors,gp), threads=self.settings.nthreads)
chx=np.random.choice(np.sum(~np.isnan(self.vels)),self.settings.nwalkers,replace=False)
dists=[np.random.normal(gp.get_parameter(nm),abs(gp.get_parameter(nm))**0.25,len(chx)) for nm in ['kernel:terms[0]:log_amp', 'kernel:terms[0]:log_timescale', 'kernel:terms[0]:log_period']]+\
[self.tcens[chx],self.bs[chx],self.vels[~np.isnan(self.vels)][chx],self.RpRss[chx],self.LD1s[chx],self.LD2s[chx]]
#'kernel:terms[0]:log_factor', 'kernel:terms[1]:log_sigma' <- frozen and not used
col=['kernel:terms[0]:log_amp', 'kernel:terms[0]:log_timescale', 'kernel:terms[0]:log_period',\
'mean:tcen','mean:b','mean:vel','mean:RpRs','mean:LD1','mean:LD2']
pos=np.column_stack(dists)
self.init_mcmc_params=pos
#print(len(pos[0,:]))
#[np.array(list(initparams.values())) *(1+ 1.5e-4*np.random.normal()) for i in range(nwalkers)]
Nsteps = 30000
sampler.run_mcmc(pos, 1, rstate0=np.random.get_state())
sampler.run_mcmc(pos, self.settings.nsteps, rstate0=np.random.get_state())
self.samples = sampler.chain[:, 3000:, :].reshape((-1, ndim))
return self.samples
#.light_curve(np.arange(0,40,0.024),texp=0.024))
'''
def SaveInput(self,stellarpdfs):
np.save(self.settings.fitsloc+self.mononame+'_inputsamples',np.column_stack(([self.pdfs[ipdf] for ipdf in self.pdfs.keys()]+[stellarpdfs[ipdf] for ipdf in stellarpdfs.keys()])))
class Lightcurve():
# Lightcurve class - contains all lightcurve information
def __init__(self, file, epic):
self.fileloc=file
self.lc,self.mag=OpenLC(self.fileloc)
try:
self.mag=k2_quickdat(epic)['k2_kepmag']
except:
self.mag=self.mag
self.lc=self.lc[~np.isnan(np.sum(self.lc,axis=1))]
self.fluxmed=np.nanmedian(self.lc[:,1])
self.lc[:,1:]/=self.fluxmed
self.lc=self.lc[AnomCutDiff(self.lc[:,1])]
self.range=self.lc[-1,0]-self.lc[self.lc[:,0]!=0.0,0][0]
self.cadence=np.nanmedian(np.diff(self.lc[:,0]))
self.lcmask=np.tile(True,len(self.lc[:,0]))
def BinLC(self, binsize,gap=0.4):
#Bins lightcurve to some time interval. Finds gaps in the lightcurve using the threshold "gap"
spl_ts=np.array_split(self.lc[:,0],np.where(np.diff(self.lc[:,0])>gap)[0]+1)
bins=np.hstack([np.arange(s[0],s[-1],binsize) for s in spl_ts])
digitized = np.digitize(self.lc[:,0], bins)
ws=(self.lc[:,2])**-2.0
ws=np.where(ws==0.0,np.median(ws[ws!=0.0]),ws)
bin_means = np.array([np.ma.average(self.lc[digitized==i,2],weights=ws[digitized==i]) for i in range(np.max(digitized))])
bin_stds = np.array([np.ma.average((self.lc[digitized==i,2]-bin_means[i])**2, weights=ws[digitized==i]) for i in range(np.max(digitized))])
whok=(~np.isnan(bin_means))&(bin_means!=0.0)
self.binlc=np.column_stack((bins,bin_means,bin_stds))[whok,:]
self.binsize=binsize
return self.binlc
'''
def keys(self):
return ['NPTS','SKY_TILE','RA_OBJ','DEC_OBJ','BMAG','VMAG','JMAG','KMAG','HMAG','PMRA','PMDEC','PMRAERR','PMDECERR','NFIELDS']
def keyvals(self,*args):
#Returns values for the given key list
arr=[]
for ke in args[0]:
exec('arr+=[self.%s]' % ke)
return arr
'''
def savelc(self):
np.save(self.settings.fitsloc+self.OBJNAME.replace(' ','')+'_bin.npy',self.get_binlc())
np.save(self.settings.fitsloc+self.OBJNAME.replace(' ','')+'.npy',self.get_lc())
def flatten(self,winsize=4.5,stepsize=0.125):
import k2flatten
return k2flatten.ReduceNoise(self.lc,winsize=winsize,stepsize=stepsize)
def calc_mask(self,meanmodels):
for model in meanmodels:
if hasattr(model,'P'):
self.lcmask[((abs(self.lc[:,0]-model.tcen)%model.P)<(self.cadence+model.tdur*0.5))+((abs(self.lc[:,0]-model.tcen)%model.P)>(model.P-(model.tdur*0.5+self.cadence)))]=False
else:
#Mono
self.lcmask[abs(self.lc[:,0]-model.tcen)<(self.cadence+model.tdur*0.5)]=False
class MonotransitModel(celerite.modeling.Model):
parameter_names = ("tcen", "b","vel","RpRs","LD1","LD2")
def get_value(self,t):
#Getting fine cadence (cad/100). Integrating later:
cad=np.median(np.diff(t))
oversamp=10#Oversampling
finetime=np.empty(0)
for i in range(len(t)):
finetime=np.hstack((finetime, np.linspace(t[i]-(1-1/oversamp)*(cad/2.), t[i]+(1-1/oversamp)*(cad/2.), oversamp) ))
finetime=np.sort(finetime)
z = np.sqrt(self.b**2+(self.vel*(finetime - self.tcen))**2)
#Removed the flux component below. Can be done by GP
model = occultquad(z, self.RpRs, np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)
'''
#TBD:
class MonotransitModel_x2(celerite.modeling.Model):
nmodels=2
parameter_names = tuple([item for sublist in [["tcen"+str(n), "b"+str(n),"vel"+str(n),"RpRs"+str(n)] for n in range(1,nmodels+1)]+[["LD1","LD2"]] for item in sublist ])
def get_value(self,t):
cad=np.median(np.diff(t))
oversamp=10#Oversampling
finetime=np.empty(0)
for i in range(len(t)):
finetime=np.hstack((finetime, np.linspace(t[i]-(1-1/oversamp)*(cad/2.), t[i]+(1-1/oversamp)*(cad/2.), oversamp) ))
finetime=np.sort(finetime)
model=np.zeros((len(finetime)))
for nmod in range(nmodels):
z = np.sqrt(getattr(self,'b'+str(nmod))**2+(getattr(self,'vel'+str(nmod))*(finetime - getattr(self,'tcen'+str(nmod))))**2)
#Removed the flux component below. Can be done by GP
model *= occultquad(z, getattr(self,'RpRs'+str(nmod)), np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)
class MonotransitModel_x3(celerite.modeling.Model):
nmodels =3
parameter_names = tuple([item for sublist in [["tcen"+str(n), "b"+str(n),"vel"+str(n),"RpRs"+str(n)] for n in range(1,nmodels+1)]+[["LD1","LD2"]] for item in sublist ])
def get_value(self,t):
cad=np.median(np.diff(t))
oversamp=10#Oversampling
finetime=np.empty(0)
for i in range(len(t)):
finetime=np.hstack((finetime, np.linspace(t[i]-(1-1/oversamp)*(cad/2.), t[i]+(1-1/oversamp)*(cad/2.), oversamp) ))
finetime=np.sort(finetime)
model=np.zeros((len(finetime)))
for nmod in range(nmodels):
z = np.sqrt(getattr(self,'b'+str(nmod))**2+(getattr(self,'vel'+str(nmod))*(finetime - getattr(self,'tcen'+str(nmod))))**2)
#Removed the flux component below. Can be done by GP
model *= occultquad(z, getattr(self,'RpRs'+str(nmod)), np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)
class MonotransitModel_plus_pl(celerite.modeling.Model):
parameter_names = ("monotcen", "monob","monovel","monoRpRs","multitcen", "multib","multiP","multiRpRs","multia_Rs","LD1","LD2")
def get_value(self,t):
cad=np.median(np.diff(t))
oversamp=10#Oversampling
finetime=np.empty(0)
for i in range(len(t)):
finetime=np.hstack((finetime, np.linspace(t[i]-(1-1/oversamp)*(cad/2.), t[i]+(1-1/oversamp)*(cad/2.), oversamp) ))
finetime=np.sort(finetime)
model=np.zeros((len(finetime)))
for nmod in range(nmodels):
z = np.sqrt(getattr(self,'b'+str(nmod))**2+(getattr(self,'vel'+str(nmod))*(finetime - getattr(self,'tcen'+str(nmod))))**2)
#Removed the flux component below. Can be done by GP
model *= occultquad(z, getattr(self,'RpRs'+str(nmod)), np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)
class MonotransitModel_plus_plx2(celerite.modeling.Model):
parameter_names = tuple(["monotcen", "monob","monovel","monoRpRs"]+
['multi'+item for sublist in [["tcen"+str(n), "b"+str(n),"P"+str(n),"RpRs"+str(n),"a_Rs"+str(n)] for n in range(1,3)]+
[["LD1","LD2"]] for item in sublist ])
def get_value(self,t):
cad=np.median(np.diff(t))
oversamp=10#Oversampling
finetime=np.empty(0)
for i in range(len(t)):
finetime=np.hstack((finetime, np.linspace(t[i]-(1-1/oversamp)*(cad/2.), t[i]+(1-1/oversamp)*(cad/2.), oversamp) ))
finetime=np.sort(finetime)
model=np.zeros((len(finetime)))
for nmod in range(nmodels):
z = np.sqrt(getattr(self,'b'+str(nmod))**2+(getattr(self,'vel'+str(nmod))*(finetime - getattr(self,'tcen'+str(nmod))))**2)
#Removed the flux component below. Can be done by GP
model *= occultquad(z, getattr(self,'RpRs'+str(nmod)), np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)
class MonotransitModelx3_plus_plx2(celerite.modeling.Model):
parameter_names = tuple(['mono'+item for sublist in [["tcen"+str(n), "b"+str(n),"vel"+str(n),"RpRs"+str(n)] for n in range(1,4)]]+\
['multi'+item for sublist in [["tcen"+str(n), "b"+str(n),"P"+str(n),"RpRs"+str(n),"a_Rs"+str(n)] for n in range(4,6)]]+\
["LD1","LD2"]])
def get_value(self,t):
cad=np.median(np.diff(t))
oversamp=10#Oversampling
finetime=np.empty(0)
for i in range(len(t)):
finetime=np.hstack((finetime, np.linspace(t[i]-(1-1/oversamp)*(cad/2.), t[i]+(1-1/oversamp)*(cad/2.), oversamp) ))
finetime=np.sort(finetime)
model=np.zeros((len(finetime)))
for nmod in range(nmodels):
z = np.sqrt(getattr(self,'b'+str(nmod))**2+(getattr(self,'vel'+str(nmod))*(finetime - getattr(self,'tcen'+str(nmod))))**2)
#Removed the flux component below. Can be done by GP
model *= occultquad(z, getattr(self,'RpRs'+str(nmod)), np.array((self.LD1,self.LD2)))
return np.average(np.resize(model, (len(t), oversamp)), axis=1)
'''
def k2_quickdat(kic):
kicdat=pd.DataFrame.from_csv("https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?table=k2targets&where=epic_number=%27"+str(int(kic))+"%27")
if len(kicdat.shape)>1:
print("Multiple entries - ",str(kicdat.shape))
kicdat=kicdat.iloc[0]
return kicdat
'''
def MonoLnPriorDict(params,priors):
lp=0
for key in priors.keys():
#print(params[n],key,priors[key])
if params[key]<priors[key][0] or params[key]>priors[key][1]:
#hidesously low number that still has gradient towards "mean" of the uniform priors.
lp-=1e15 * (params[key]-(0.5*(priors[key][0]+priors[key][1])))**2
#print(key," over prior limit")
if len(priors[key])>2:
if priors[key][2]=='gaussian':
lp+=stats.norm(priors[key][3],priors[key][4]).pdf(params[key])
elif priors[key][2]=='normlim':
#Special velocity prior from min period & density:
lp+=((1.0-stats.norm.cdf(params[key],priors[key][3],priors[key][4]))*params[key])**2
return lp
'''
def MonoLnPrior(params,priors):
lp=0
for n,key in enumerate(priors.keys()):
#print(params[n],key,priors[key])
if params[n]<priors[key][0] or params[n]>priors[key][1]:
#hideously low number that still has gradient towards "mean" of the uniform priors. Scaled by prior width
lp-=1e20 * (((params[n]-0.5*(priors[key][0]+priors[key][1])))/(priors[key][1]-priors[key][0]))**2
#print(key," over prior limit")
if len(priors[key])>2:
if priors[key][2]=='gaussian':
lp+=stats.norm(priors[key][3],priors[key][4]).pdf(params[n])
elif priors[key][2]=='normlim':
#Special velocity prior from min period & density:
lp+=((1.0-stats.norm.cdf(params[n],priors[key][3],priors[key][4]))*params[n])**2
elif priors[key][2]=='evans':
#Evans 2015 limit on amplitude - same as p(Ai) = Gam(1, 100) (apparently, although I cant see it.)
#Basically prior is ln
lp-=priors[key][3]*np.exp(params[n])#
return lp
def MonoLogProb(params,lc,priors,gp):
gp.set_parameter_vector(params)
gp.compute(lc[:,0],lc[:,2])
ll = gp.log_likelihood(lc[:,1])
lp = MonoLnPrior(params,priors)
return (ll+lp)
def MonoNegLogProb(params,lc,priors,gp):
return -1*MonoLogProb(params,lc,priors,gp)
def MonoOnlyLogProb(params,lc,priors,monomodel):
monomodel.set_parameter_vector(params)
ll = np.sum(-2*lc[:,2]**-2*(lc[:,1]-monomodel.get_value(lc[:,0]))**2)#-(0.5*len(lc[:,0]))*np.log(2*np.pi*lc[:,2]**2) #Constant not neceaary for gradient descent
lp = MonoLnPrior(params,priors)
return (ll+lp)
def MonoOnlyNegLogProb(params,lc,priors,monomodel):
return -1*MonoOnlyLogProb(params,lc,priors,monomodel)
class RotationTerm(celerite.terms.Term):
parameter_names = ("log_amp", "log_timescale", "log_period", "log_factor")
def get_real_coefficients(self, params):
log_amp, log_timescale, log_period, log_factor = params
f = np.exp(log_factor)
return (
np.exp(log_amp) * (1.0 + f) / (2.0 + f),
np.exp(-log_timescale),
)
def get_complex_coefficients(self, params):
log_amp, log_timescale, log_period, log_factor = params
f = np.exp(log_factor)
return (
np.exp(log_amp) / (2.0 + f),
0.0,
np.exp(-log_timescale),
2*np.pi*np.exp(-log_period),
)
def neg_log_like(params, y, gp):
gp.set_parameter_vector(params)
return -gp.log_likelihood(y)
def grad_neg_log_like(params, y, gp):
gp.set_parameter_vector(params)
return -gp.grad_log_likelihood(y)[1]
'''
def grad_nll(p,gp,y,prior=[]):
#Gradient of the objective function for TrainGP
gp.set_parameter_vector(p)
return -gp.grad_log_likelihood(y, quiet=True)
def nll_gp(p,gp,y,prior=[]):
#inverted LnLikelihood function for GP training
gp.set_parameter_vector(p)
if prior!=[]:
prob=MonoLogProb(p,y,prior,gp)
return -prob if np.isfinite(prob) else 1e25
else:
ll = gp.log_likelihood(y, quiet=True)
return -ll if np.isfinite(ll) else 1e25'''
def VelToOrbit(vel, Rs, Ms, ecc=0, omega=0,timebin=86400.0):
'''Takes in velocity (in units of stellar radius), Stellar radius estimate and (later) eccentricity & angle of periastron.
Returns Semi major axis (AU) and period (days)'''
Rs=Rs*695500000# if Rs<5 else Rs
Ms=Ms*1.96e30# if Ms<5 else Ms
SMA=(6.67e-11*Ms)/((vel*Rs/86400.)**2)
Per=(2*np.pi*SMA)/(vel*Rs/86400)
return SMA/1.49e11, Per/86400
def getKeplerLDs(Ts,logg=4.43812,FeH=0.0,how='2'):
#Get Kepler Limb darkening coefficients.
from scipy.interpolate import CloughTocher2DInterpolator as ct2d
#print(label)
types={'1':[3],'2':[4, 5],'3':[6, 7, 8],'4':[9, 10, 11, 12]}
if how in types:
checkint = types[how]
#print(checkint)
else:
print("no key...")
arr = np.genfromtxt("KeplerLDlaws.txt",skip_header=2)
FeHarr=np.unique(arr[:, 2])
#Just using a single value of FeH
if not (type(FeH)==float) and not (type(FeH)==int):
FeH=np.nanmedian(FeH)
FeH=FeHarr[find_nearest(FeHarr,FeH)]
feh_ix=arr[:,2]==FeH
feh_ix=arr[:,2]==FeH
Tlen=1 if type(Ts)==float or type(Ts)==int else len(Ts)
outarr=np.zeros((Tlen,len(checkint)))
for n,i in enumerate(checkint):
u_interp=ct2d(np.column_stack((arr[feh_ix,0],arr[feh_ix,1])),arr[feh_ix,i])
if (type(Ts)==float)+(type(Ts)==int) and ((Ts<50000.)*(Ts>=2000)):
outarr[0,n]=u_interp(Ts,logg)
elif ((Ts<50000.)*(Ts>=2000)).all():
if type(logg)==float:
outarr[:,n]=np.array([u_interp(T,logg) for T in Ts])
else:
outarr[:,n]=np.array([u_interp(Ts[t],logg[t]) for t in range(len(Ts))])
else:
print('Temperature outside limits')
outarr=None
break
return outarr
def nonan(lc):
return np.logical_not(np.isnan(np.sum(lc,axis=1)))
def AnomCutDiff(flux,thresh=4.2):
#Uses differences between points to establish anomalies.
#Only removes single points with differences to both neighbouring points greater than threshold above median difference (ie ~rms)
#Fast: 0.05s for 1 million-point array.
#Must be nan-cut first
diffarr=np.vstack((np.diff(flux[1:]),np.diff(flux[:-1])))
diffarr/=np.median(abs(diffarr[0,:]))
anoms=np.hstack((True,((diffarr[0,:]*diffarr[1,:])>0)+(abs(diffarr[0,:])<thresh)+(abs(diffarr[1,:])<thresh),True))
return anoms
def CalcTdur(vel, b, p):
'''Caculates a velocity (in v/Rs) from the input transit duration Tdur, impact parameter b and planet-to-star ratio p'''
# In Rs per day
return (2*(1+p)*np.sqrt(1-(b/(1+p))**2))/vel
def CalcVel(Tdur, b, p):
'''Caculates a velocity (in v/Rs) from the input transit duration Tdur, impact parameter b and planet-to-star ratio p'''
# In Rs per day
return (2*(1+p)*np.sqrt(1-(b/(1+p))**2))/Tdur
def PlotBestMono(lc, monomodel, vector, fname=None):
cad=np.median(np.diff(lc[:,0]))
t=np.arange(lc[0,0],lc[-1,0]+0.01,cad)
monomodel.set_parameter_vector(vector)
ypred=monomodel.get_value(t)
plt.errorbar(lc[:, 0], lc[:,1], yerr=lc[:, 2], fmt='.',color='#999999')
plt.plot(lc[:, 0], lc[:,1], '.',color='#333399')
plt.plot(t,ypred,'--',color='#003333',linewidth=2.0,label='Median transit model fit')
if fname is not None:
plt.savefig(fname)
def PlotModel(lc, model, vector, prevmodels=[], plot=True, residuals=False, scale=1, nx=10000, GP=False, subGP=False, monomodel=0, verbose=True,fname=None):
# - lc : lightcurve
# - model : celerite-style model (eg gp) to apply the vector to
# - vector : best-fit parameters to use
cad=np.median(np.diff(lc[:,0]))
t=np.arange(lc[0,0],lc[-1,0]+0.01,cad)
if len(prevmodels)==0:
model.set_parameter_vector(vector)
model.compute(lc[:,0],lc[:,2])
ypreds,varpreds=model.predict(lc[:,1], t)
stds=np.sqrt(np.diag(varpreds))
model.mean.get_value(t)
modelfits=np.column_stack((ypreds-stds*2,ypreds-stds,ypreds,ypreds+stds,ypreds+stds*2,model.mean.get_value(t)))
else:
modelfits=prevmodels
if residuals:
#Subtracting bestfit model from both flux and model to give residuals
newmodelfits=np.column_stack((modelfits[:,:5]-np.tile(modelfits[:,2], (5, 1)).swapaxes(0, 1),modelfits[:,5])) #subtracting median fit
Ploty=lc[:,1]-modelfits[:, 2][(np.round((lc[:,0]-lc[0,0])/0.020431700249901041)).astype(int)]
#p.xlim([t[np.where(redfits[:,2]==np.min(redfits[:,2]))]-1.6, t[np.where(redfits[:,2]==np.min(redfits[:,2]))]+1.6])
nomys=None #Not plotting the non-GP model.
elif subGP:
newmodelfits=np.column_stack((modelfits[:,:5]-np.tile(nomys, (5, 1)).swapaxes(0, 1),modelfits[:,5])) #subtracting median fit
Ploty=lc[:,1]-modelfits[:,5]
#p.xlim([t[np.where(redfits[:,2]==np.min(redfits[:,2]))]-1.6, t[np.where(redfits[:,2]==np.min(redfits[:,2]))]+1.6])
nomys=None #Not plotting the non-GP model.
else:
Ploty=lc[:,1]
newmodelfits=np.copy(modelfits)
if plot:
plt.errorbar(lc[:, 0], lc[:,1], yerr=lc[:, 2], fmt=',',color='#999999',alpha=0.8,zorder=-100)
plt.plot(lc[:, 0], lc[:,1], '.',color='#333399')
#Plotting 1-sigma error region and models
print(np.shape(newmodelfits))
plt.fill(np.hstack((t,t[::-1])),
np.hstack((newmodelfits[:,2]-(newmodelfits[:,2]-newmodelfits[:,1]),(newmodelfits[:,2]+(newmodelfits[:,3]-newmodelfits[:,2]))[::-1])),
'#3399CC', linewidth=0,label='$1-\sigma$ region ('+str(scale*100)+'% scaled)',alpha=0.5)
plt.fill(np.hstack((t,t[::-1])),
np.hstack(((1.0+newmodelfits[:,2]-newmodelfits[:,5])-(newmodelfits[:,2]-newmodelfits[:,1]),((1.0+newmodelfits[:,2]-newmodelfits[:,5])+(newmodelfits[:,3]-newmodelfits[:,2]))[::-1])),
'#66BBCC', linewidth=0,label='$1-\sigma$ region without transit',alpha=0.5)
plt.plot(t,modelfits[:,2],'-',color='#003333',linewidth=2.0,label='Median model fit')
if not residuals and not subGP:
plt.plot(t,model.mean.get_value(t),'--',color='#003333',linewidth=2.0,label='Median transit model fit')
if not residuals and not subGP:
#Putting title on upper (non-residuals) graph
plt.title('Best fit model')
plt.legend(loc=3,fontsize=9)
if fname is not None:
plt.savefig(fname)
return modelfits
| 66,119 | 50.495327 | 252 | py |
Namaste | Namaste-master/namaste/k2flatten.py | import numpy as np
#import pyfits
#import hpo.planetlib as pl
def dopolyfit(win,d,ni,sigclip):
base = np.polyfit(win[:,0],win[:,1],w=1.0/np.power(win[:,2],2),deg=d)
#for n iterations, clip 3(?) sigma, redo polyfit
for iter in range(ni):
#winsigma = np.std(win[:,1]-np.polyval(base,win[:,0]))
offset = np.abs(win[:,1]-np.polyval(base,win[:,0]))/win[:,2]
clippedregion = win[offset<sigclip,:]
if (offset<sigclip).sum()>int(0.8*len(win[:, 0])):
clippedregion = win[offset<sigclip,:]
else:
clippedregion=win[offset<np.average(offset)]
base = np.polyfit(clippedregion[:,0],clippedregion[:,1],w=1.0/np.power(clippedregion[:,2],2),deg=d)
return base
def formwindow(dat,cent,size,boxsize,gapthresh):
winlowbound = np.searchsorted(dat[:,0],cent-size/2.)
winhighbound = np.searchsorted(dat[:,0],cent+size/2.)
boxlowbound = np.searchsorted(dat[:,0],cent-boxsize/2.)
boxhighbound = np.searchsorted(dat[:,0],cent+boxsize/2.)
if winhighbound == len(dat[:,0]):
winhighbound -= 1
highgap = dat[winhighbound,0] < (cent+size/2.)-gapthresh #uses a 1d threshold for gaps
lowgap = dat[winlowbound,0] > (cent-size/2.)+gapthresh
flag = 0
if highgap:
if lowgap:
flag = 1
else:
winlowbound = np.searchsorted(dat[:,0],dat[winhighbound,0]-size)
else:
if lowgap:
winhighbound = np.searchsorted(dat[:,0],dat[winlowbound,0]+size)
window = np.concatenate((dat[winlowbound:boxlowbound,:],dat[boxhighbound:winhighbound,:]))
box = dat[boxlowbound:boxhighbound,:]
return window,boxlowbound,boxhighbound
if __name__ == '__main__':
RedFromFile(sys.argv[1], sys.argv[2])
def ReadFromFile(fname):
outlc=ReduceNoise(pl.ReadLC(fname))
np.savetxt(fnameout, outlc)
def ReduceNoise(lc2, winsize = 2, stepsize = 0.2, polydegree = 3, niter = 20, sigmaclip = 3., gapthreshold = 1.0 ):
'''set up flattening parameters
winsize = 2 #days, size of polynomial fitting region
stepsize = 0.2 #days, size of region within polynomial region to detrend
polydegree = 3 #degree of polynomial to fit to local curve
niter = 20 #number of iterations to fit polynomial, clipping points significantly deviant from curve each time.
sigmaclip = 3. #significance at which points are clipped (as niter)
gapthreshold = 1.0 #days, threshold at which a gap in the time series is detected and the local curve is adjusted to not run over it
'''
lc=np.copy(lc2)
lcdetrend=np.column_stack((lc[:, 0], np.zeros(len(lc[:, 0])), lc[:, 2]))
#general setup
JD0 = lc[0,0]
lc[:,0] = lc[:,0] - JD0
#lcdet[:,0] = lcdet[:,0] - JD0
lenlc = lc[-1,0]
lcbase = np.median(lc[:,1])
lc[:,1] /= lcbase
lc[:,2] = lc[:,2]/lcbase
nsteps = np.ceil(lenlc/stepsize).astype('int')
stepcentres = np.arange(nsteps)/float(nsteps) * lenlc + stepsize/2.
#print nsteps
#for each step centre:
#actual flattening
for s in range(nsteps):
stepcent = stepcentres[s]
winregion,boxlowbound,boxhighbound = formwindow(lc,stepcent,winsize,stepsize,gapthreshold) #should return window around box not including box
baseline = dopolyfit(winregion,polydegree,niter,sigmaclip)
lcdetrend[boxlowbound:boxhighbound, 1] = lc[boxlowbound:boxhighbound,1] - np.polyval(baseline,lc[boxlowbound:boxhighbound,0]) + 1
# winregiondet,boxlowbounddet,boxhighbounddet = formwindow(lcdet,stepcent,winsize,stepsize,gapthreshold) #should return window around box not including box
# baselinedet = dopolyfit(winregiondet,polydegree,niter,sigmaclip)
# lcdetdetrend[boxlowbounddet:boxhighbounddet] = lcdet[boxlowbounddet:boxhighbounddet,1] - np.polyval(baselinedet,lcdet[boxlowbounddet:boxhighbounddet,0]) + 1
return lcdetrend
| 3,881 | 44.670588 | 165 | py |
Namaste | Namaste-master/namaste/__init__.py | __all__=["namaste", "planetlib","Crossfield_transit"]
from . import namaste
from . import planetlib
#from . import k2flatten
from . import Crossfield_transit
| 158 | 25.5 | 53 | py |
InvariantRuleAD | InvariantRuleAD-main/core/__init__.py | 0 | 0 | 0 | py | |
InvariantRuleAD | InvariantRuleAD-main/core/learning/__init__.py | 0 | 0 | 0 | py | |
InvariantRuleAD | InvariantRuleAD-main/core/learning/hp_optimization/Hyperparameter.py | from abc import ABC,abstractmethod
import random
from enum import Enum
class HyperparameterType(Enum):
UniformInteger = 301
UniformFloat = 302
Categorical = 303
Const = 304
class baseHyperparameter(ABC):
'''
The base class for Hyperparameters
Parameters
----------
name : string
the name of the hyperparameter
hp_type : HyperparameterType
the type of the hyperparameter
'''
def __init__(self,name,hp_type):
'''
Constructor
'''
self._name = name
self._hp_type = hp_type
@abstractmethod
def getValue(self):
'''
Get a value of the hyperparameter
Returns
-------
Object
the value
'''
pass
@abstractmethod
def getAllValues(self):
'''
Get all possible values for the hyperparameter
Returns
-------
list or tuple
the all possible values
'''
pass
@property
def name(self):
"""Get the name."""
return self._name
@property
def hp_type(self):
"""Get the type."""
return self._hp_type
class UniformIntegerHyperparameter(baseHyperparameter):
'''
The uniform integer hyperparameter class
Parameters
----------
name : string
the name of the hyperparameter
lb : int
the lower bound of the hyperparameter, inclusive
ub : int
the upper bound of the hyperparameter, inclusive
'''
def __init__(self, name, lb, ub):
'''
Constructor
'''
self.bot = lb
self.top = ub
super().__init__(name,HyperparameterType.UniformInteger)
def getValue(self):
'''
Get a random value of the hyperparameter
Returns
-------
int
a random value between [lb,ub]
'''
return random.randint(self.bot,self.top)
def getAllValues(self):
'''
Get all possible values for the hyperparameter
Returns
-------
tuple
a tuple including the lower bound and upper bound of the hyperparameter
'''
return (self.bot,self.top)
class UniformFloatHyperparameter(baseHyperparameter):
'''
The uniform float hyperparameter class
Parameters
----------
name : string
the name of the hyperparameter
lb : float
the lower bound of the hyperparameter, inclusive
ub : float
the upper bound of the hyperparameter, inclusive
'''
def __init__(self, name, lb, ub):
'''
Constructor
'''
self.bot = lb
self.top = ub
super().__init__(name,HyperparameterType.UniformFloat)
def getValue(self):
'''
Get a random value of the hyperparameter
Returns
-------
float
a random value between [lb,ub]
'''
return random.uniform(self.bot,self.top)
def getAllValues(self):
'''
Get all possible values for the hyperparameter
Returns
-------
tuple
a tuple including the lower bound and upper bound of the hyperparameter
'''
return (self.bot,self.top)
class CategoricalHyperparameter(baseHyperparameter):
'''
The categorical hyperparameter class
Parameters
----------
name : string
the name of the hyperparameter
value_list : list
the list of all possible values of the hyperparameter
'''
def __init__(self, name, value_list):
'''
Constructor
'''
self.value_list = value_list
super().__init__(name,HyperparameterType.Categorical)
def getValue(self):
'''
Get a random value of the hyperparameter
Returns
-------
object
a random value in value_list
'''
idx = random.randint(0,len(self.value_list)-1)
return self.value_list[idx]
def getAllValues(self):
'''
Get all possible values for the hyperparameter
Returns
-------
list
the value list
'''
return self.value_list
class ConstHyperparameter(baseHyperparameter):
'''
The constant hyperparameter class
Parameters
----------
name : string
the name of the hyperparameter
value : object
the value of the hyperparameter
'''
def __init__(self, name, value):
'''
Constructor
'''
self.value = value
super().__init__(name,HyperparameterType.Const)
def getValue(self):
'''
Get the value of the hyperparameter
Returns
-------
object
the value
'''
return self.value
def getAllValues(self):
'''
Get all possible values for the hyperparameter
Returns
-------
list
a list only has one member, the value
'''
return [self.value]
| 5,276 | 21.172269 | 83 | py |
InvariantRuleAD | InvariantRuleAD-main/core/learning/hp_optimization/HPOptimizers.py | import itertools,collections
from .Hyperparameter import HyperparameterType
class RandomizedGridSearch(object):
'''
The utility class for hyperparameters tuning of ML models based on Randomized Grid Search.
Parameters
----------
model : BaseModel
The model, should be an object extends BaseModel
hyperparameters : list
The list of hyperparameters of the ML model
train_data : ndarray or list of ndarray
the training data
val_data : ndarray or list of ndarray
the validation data
'''
def __init__(self, model, hyperparameters, train_data, val_data):
'''
Constructor
'''
self._model = model
self._hyperparameters = hyperparameters
self._train_data = train_data
self._val_data = val_data
def _eval(self, **args):
self._model.train(self._train_data,self._val_data,**args)
score = self._model.score(self._val_data)
if score > self._best_score:
self._model.save_model()
self._best_score = score
self._best_config = args.copy()
return score
def run(self, n_searches ,verbose=0):
'''
Run the randomized grid search algorithm to find the best hyperparameter configuration for the ML model
Parameters
----------
n_searches : int
the number of searches
verbose : int, default is 0
higher level of verbose prints more messages during running the algorithm
Returns
-------
BaseModel
the optimized model
dict
the hyperparameter configuration of the optimized model
float
the best score achieved by the optimized model
'''
self._best_score = float('-inf')
random_mode = False
for hp in self._hyperparameters:
if hp.hp_type != HyperparameterType.Const and hp.hp_type != HyperparameterType.Categorical:
random_mode = True
break
if random_mode == False:
param_lists = []
for hp in self._hyperparameters:
param_lists.append(hp.getAllValues())
candidates = list(itertools.product(*param_lists))
if len(candidates) > n_searches:
random_mode = True
if random_mode:
candidates = []
for _ in range(n_searches):
param_list = []
for hp in self._hyperparameters:
param_list.append(hp.getValue())
isDup = False
for can in candidates:
if collections.Counter(can) == collections.Counter(param_list):
isDup = True
break
if isDup == False:
candidates.append(param_list)
for can in candidates:
i = 0
can_dict = {}
for hp in self._hyperparameters:
can_dict[hp.name] = can[i]
i += 1
score = self._eval(**can_dict)
if verbose > 0:
print('score:', score, can_dict)
self._model.load_model()
return self._model, self._best_config, self._best_score
| 3,373 | 31.757282 | 111 | py |
InvariantRuleAD | InvariantRuleAD-main/core/learning/hp_optimization/__init__.py | 0 | 0 | 0 | py | |
InvariantRuleAD | InvariantRuleAD-main/core/utils/metrics.py | from sklearn.metrics import confusion_matrix
def calc_detection_performance(y_true, y_pred):
"""
calculate anomaly detection performance
Parameters
----------
y_true : ndarray or list
The ground truth labels
y_pred : ndarray or list
The predicted labels
Returns
-------
list
list for results, [f1,precision,recall,TP,TN,FP,FN]
"""
TN,FP,FN,TP = confusion_matrix(y_true,y_pred).ravel()
precision = TP / (TP + FP + 0.00001)
recall = TP / (TP + FN + 0.00001)
f1 = 2 * precision * recall / (precision + recall + 0.00001)
return [f1,precision,recall,TP, TN, FP, FN]
| 660 | 23.481481 | 64 | py |
InvariantRuleAD | InvariantRuleAD-main/core/utils/__init__.py | def override(f):
return f | 29 | 14 | 16 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/base.py | from abc import ABC, abstractmethod
import tempfile
import os
import warnings
class BaseModel(ABC):
"""
The base class
"""
@abstractmethod
def train(self, train_data, val_data=None, **params):
"""
Create a model based on the give hyperparameters and train the model
Parameters
----------
train_data : ndarray
the numpy array from where the training samples are extracted
val_data : ndarray, default is None
the numpy array from where the validation samples are extracted
params : dict
the hyperparameters of the model
Returns
-------
BaseModel
self
"""
pass
@abstractmethod
def predict(self, data):
"""
Predict outputs for x
Parameters
----------
data : ndarray
the numpy array from where the samples are extracted
Returns
-------
ndarray or list of ndarray
the output data
"""
pass
@abstractmethod
def score(self, data):
"""
Score the model based on its performance on given data.
A higher score indicates a better performance.
Parameters
----------
data : ndarray
the numpy array from where the samples are extracted
Returns
-------
float
the score
"""
pass
# @abstractmethod
# def get_default_hyperparameters(self):
# """
# get the default values or ranges of hyperparameters for tuning
#
# Returns
# -------
# list
# list of Hyperparameters
# """
# pass
def save_model(self, model_path=None, model_id=None):
"""
save the model to files
Parameters
----------
model_path : string, default is None
the target folder whether the model files are saved.
If None, a tempt folder is created
model_id : string, default is None
the id of the model, must be specified when model_path is not None
Returns
-------
string
the path to load the model
"""
if model_path is None:
model_path = tempfile.gettempdir()
else:
if model_id is None:
warnings.warn('Please specify model id')
model_path = model_path+'/'+model_id
if not os.path.exists(model_path):
os.makedirs(model_path)
return model_path
def load_model(self, model_path=None,model_id=None):
"""
load the model from files
Parameters
----------
model_path : string, default is None
the target folder whether the model files are located
If None, load models from the tempt folder
model_id : string, default is None
the id of the model, must be specified when model_path is not None
Returns
-------
string
the path to load the model
"""
if model_path is None:
model_path = tempfile.gettempdir()
else:
if model_id is None:
warnings.warn('Please specify model id')
model_path = model_path+'/'+model_id
return model_path
class AnomalyDetector(ABC):
"""
The abstract class for all anomaly detectors in predictive_maintenance
"""
@abstractmethod
def score_samples(self, **params):
"""
get the anomaly scores for the input samples
Parameters
----------
params : dict
input parameters
"""
pass
| 3,945 | 23.81761 | 78 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/__init__.py | from .base import BaseModel,AnomalyDetector
from enum import Enum
__all__ = ['BaseModel','AnomalyDetector'] | 108 | 26.25 | 43 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/reconstruction_models/DeepSVDD.py | import numpy as np
import tensorflow as tf
from tensorflow import keras
import tempfile
from .. import BaseModel
import random
def oneclass_loss(z,radius,nu):
dist = tf.reduce_sum(tf.square(z), axis=-1)
loss = tf.maximum(dist - radius ** 2, tf.zeros_like(dist))
loss = radius**2+(1/nu)*tf.reduce_mean(loss)
return loss
class DeepSVDD(BaseModel):
def __init__(self, signals):
self.signals = signals
self.targets = []
for signal in self.signals:
if signal.isInput and signal.isOutput:
self.targets.append(signal.name)
def score_samples(self, x):
z = self._model.predict(x)
dists = []
for t in range(len(x)):
z_t = z[t]
dist = np.sum(np.square(z_t))
dists.append(dist)
return np.array(dists)
def predict(self,x):
z = self.estimator.predict(x)
return z
def _get_train_fn(self):
@tf.function
def _train_step(x,model,radius,nu,optimizer):
with tf.GradientTape() as tape:
z = model(x)
loss = oneclass_loss(z,radius,nu)
gradients = tape.gradient(loss, model.trainable_variables+[radius])
optimizer.apply_gradients(zip(gradients, model.trainable_variables+[radius]))
return loss
return _train_step
def train(self, x, z_dim, nu=0.1, hidden_layers=1, z_activation='tanh', batch_size=256,epochs=10, verbose=0):
np.random.seed(123)
random.seed(1234)
tf.random.set_seed(1234)
keras.backend.clear_session()
model = self._make_network(x.shape[1], z_dim, hidden_layers,z_activation)
# model.summary()
radius = tf.Variable(0.1, dtype=np.float32)
optimizer = tf.keras.optimizers.Adam()
train_fn = self._get_train_fn()
verbose_interval = epochs//10
for ep in range(epochs):
shuffle_index = np.arange(len(x))
np.random.shuffle(shuffle_index)
x = x[shuffle_index]
ep_loss = 0
iter_num = int(x.shape[0]//batch_size)
for i in range(iter_num):
batch_x = x[i*batch_size:(i+1)*batch_size].astype(np.float32)
loss = train_fn(batch_x,model,radius,nu,optimizer)
ep_loss += loss
if verbose and ep % verbose_interval == 0:
print('epoch:',ep,'/',epochs)
print('loss',ep_loss/iter_num)
print('radius',radius)
print('dloss',loss)
print()
self._model = model
return self
def score(self,neg_x,neg_y):
"""
Score the model based on datasets with uniform negative sampling.
Better score indicate a higher performance
For efficiency, the best f1 score of NSIBF-PRED is used for scoring in this version.
"""
pass
def save_model(self,model_path=None):
"""
save the model to files
:param model_path: the target folder whether the model files are saved (default is None)
If None, a tempt folder is created
"""
if model_path is None:
model_path = tempfile.gettempdir()
self.estimator.save(model_path+'/OCAE.h5',save_format='h5')
def load_model(self,model_path=None):
"""
load the model from files
:param model_path: the target folder whether the model files are located (default is None)
If None, load models from the tempt folder
:return self
"""
if model_path is None:
model_path = tempfile.gettempdir()
self.estimator = keras.models.load_model(model_path+'/OCAE.h5')
return self
def _make_network(self, x_dim, z_dim, hidden_layers,z_activation='relu'):
hidden_dims = []
interval = (x_dim-z_dim)//(hidden_layers+1)
x_input = keras.Input(shape=(x_dim),name='x_input')
for i in range(hidden_layers):
hid_dim = max(1,x_dim-interval*(i+1))
hidden_dims.append(hid_dim)
if i == 0:
g_dense = keras.layers.Dense(hid_dim, activation='relu') (x_input)
else:
g_dense = keras.layers.Dense(hid_dim, activation='relu') (g_dense)
z_out = keras.layers.Dense(z_dim, activation=z_activation,name='z_output')(g_dense)
model = keras.Model(x_input,z_out)
return model
| 4,639 | 32.623188 | 113 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/reconstruction_models/vanilla_autoencoder.py | from tensorflow import keras
import tensorflow as tf
import numpy as np
import tempfile
import random
from .. import BaseModel,AnomalyDetector
from ...preprocessing.signals import ContinuousSignal,CategoricalSignal
from ...learning.hp_optimization.Hyperparameter import ConstHyperparameter,UniformIntegerHyperparameter
from ...utils import override
from sklearn import metrics
from ...preprocessing.data_handler import TSAEDataHandler
from ...preprocessing.data_util import signals2dfcolumns
class Autoencoder(BaseModel,AnomalyDetector):
'''
The vanilla version of autoencoder for anomaly detection
Parameters
----------
signals : list
the list of signals the model is dealing with.
Signals that are both input and output will be included.
sequence_length : int, default is 1
the length of input sequence
'''
def __init__(self, signals,sequence_length=1):
self.l = sequence_length
self.signals = signals
self.estimator = None
self.feats = []
for signal in self.signals:
if signal.isInput and signal.isOutput:
if isinstance(signal, ContinuousSignal):
self.feats.append(signal.name)
if isinstance(signal, CategoricalSignal):
self.feats.extend(signal.get_onehot_feature_names())
df_columns = signals2dfcolumns(signals)
self._data_handler = TSAEDataHandler(sequence_length, self.feats, df_columns)
@property
def data_handler(self):
"""
get the data handler
Returns
-------
TSAEDataHandler
the data handler
"""
return self._data_handler
@override
def score_samples(self, data, return_evidence=False):
"""
get the anomaly scores for the input samples
Parameters
----------
data : ndarray
the numpy array from where the samples are extracted
return_evidence : bool, default is False
whether to return observation and reconstruction for evidence
Returns
-------
ndarray
the anomaly scores, matrix of shape = [n_samples,]
ndarray (only return when return_evidence=True)
the ground truth values, matrix of shape = [n_samples,n_features]
ndarray (only return when return_evidence=True)
the reconstructed values, matrix of shape = [n_samples,n_features]
"""
x,_ = self._data_handler.extract_data4AD(data, mode='block', stride=self.l)
y_pred = self.estimator.predict(x)
anomaly_scores = []
for i in range(len(x)):
err = metrics.mean_absolute_error(x[i],y_pred[i])
anomaly_scores.append(err)
if return_evidence:
y_pred = np.reshape(y_pred,(-1,len(self.feats)))
x = np.reshape(x,(-1,len(self.feats)))
return np.array(anomaly_scores),x,y_pred
else:
return np.array(anomaly_scores)
@override
def get_default_hyperparameters(self,verbose):
"""
get the default values or ranges of hyperparameters for tuning
Parameters
----------
verbose : int
higher values indicate more messages will be printed
Returns
-------
list
list of Hyperparameters
"""
hp_list = []
hp_list.append(ConstHyperparameter('hidden_dim',len(self.feats)//2))
hp_list.append(UniformIntegerHyperparameter('num_hidden_layers',1,3))
hp_list.append(ConstHyperparameter('epochs',100))
hp_list.append(ConstHyperparameter('verbose',verbose))
return hp_list
@override
def train(self, train_data, val_data, hidden_dim, num_hidden_layers=1,
optimizer='adam',batch_size=256,epochs=10,
save_best_only=False, set_seed=False,verbose=0):
"""
Build and train a vanilla version of autoencoder
Parameters
----------
train_data : ndarray or list of ndarray
the numpy array from where the training samples are extracted
val_data : ndarray or list of ndarray
the numpy array from where the validation samples are extracted
hidden_dim : int
the latent dimension of encoder and decoder layers
num_hidden_layers : int, default is 1
the number of hidden LSTM layers
optimizer : string or optimizer, default is 'adam'
the optimizer for gradient descent
batch_size : int, default is 256
the batch size
epochs : int, default is 10
the maximum epochs to train the model
save_best_only : int, default is True
whether to save the model with best validation performance during training
set_seed: bool, default is False
whether to set random seed for reproducibility
verbose : int, default is 0
0 indicates silent, higher values indicate more messages will be printed
Returns
-------
Autoencoder
self
"""
keras.backend.clear_session()
if set_seed:
np.random.seed(123)
random.seed(1234)
tf.random.set_seed(1234)
input_dim = self.l * len(self.feats)
self.estimator = self._make_network(input_dim, hidden_dim, num_hidden_layers)
self.estimator.compile(optimizer=optimizer,loss='mse')
train_ds = self._data_handler.make_dataset(train_data, 'block', batch_size)
val_ds = self._data_handler.make_dataset(val_data, 'block', batch_size)
if save_best_only:
checkpoint_path = tempfile.gettempdir()+'/Autoencoder.ckpt'
cp_callback = keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,save_best_only=True, save_weights_only=True)
self.estimator.fit(train_ds, epochs=epochs, validation_data = val_ds, callbacks=[cp_callback], verbose=verbose)
self.estimator.load_weights(checkpoint_path)
else:
self.estimator.fit(train_ds, epochs=epochs, validation_data = val_ds, verbose=verbose)
return self
@override
def predict(self, data):
"""
Predict the reconstructed samples
Parameters
----------
data : ndarray
the numpy array from where the samples are extracted
Returns
-------
ndarray
the reconstructed outputs, matrix of shape = [n_samples, n_feats]
"""
if self.estimator is None:
return None
x = self._data_handler.extract_data4predict(data, 'block', stride=self.l)
y_hat = self.estimator.predict(x)
y_pred = np.reshape(y_hat,(-1,len(self.feats)))
return y_pred
@override
def score(self,data):
"""
Calculate the negative MAE score on the given data.
Parameters
----------
data : ndarray
the numpy array from where the samples are extracted
Returns
-------
float
the negative mae score
"""
x,y = self._data_handler.extract_data4AD(data, 'block', stride=1)
y_hat = self.estimator.predict(x)
score = np.abs(y-y_hat).mean()
return -score
@override
def save_model(self,model_path=None, model_id=None):
"""
save the model to files
Parameters
----------
model_path : string, default is None
the target folder whether the model files are saved.
If None, a tempt folder is created
model_id : string, default is None
the id of the model, must be specified when model_path is not None
"""
model_path = super().save_model(model_path, model_id)
self.estimator.save(model_path+'/Autoencoder.h5')
@override
def load_model(self,model_path=None, model_id=None):
"""
load the model from files
Parameters
----------
model_path : string, default is None
the target folder whether the model files are located
If None, load models from the tempt folder
model_id : string, default is None
the id of the model, must be specified when model_path is not None
Returns
-------
Autoencoder
self
"""
model_path = super().load_model(model_path, model_id)
self.estimator = keras.models.load_model(model_path+'/Autoencoder.h5')
return self
def _make_network(self, input_dim, hidden_dim, num_hidden_layers):
x_t = keras.Input(shape=(input_dim),name='x_t')
interval = (input_dim-hidden_dim)//(num_hidden_layers+1)
hidden_dims = []
hid_dim = max(1,input_dim-interval)
hidden_dims.append(hid_dim)
f_dense1 = keras.layers.Dense(hid_dim, activation='relu',name='g_dense1')(x_t)
for i in range(1,num_hidden_layers):
hid_dim = max(1,input_dim-interval*(i+1))
if i == 1:
f_dense = keras.layers.Dense(hid_dim, activation='relu') (f_dense1)
else:
f_dense = keras.layers.Dense(hid_dim, activation='relu') (f_dense)
hidden_dims.append(hid_dim)
if num_hidden_layers > 1:
z_layer = keras.layers.Dense(hidden_dim,name='z_layer')(f_dense)
else:
z_layer = keras.layers.Dense(hidden_dim,name='z_layer')(f_dense1)
g_dense1 = keras.layers.Dense(hidden_dims[len(hidden_dims)-1], activation='relu',name='h_dense1')(z_layer)
for i in range(1,num_hidden_layers):
if i == 1:
g_dense = keras.layers.Dense(hidden_dims[len(hidden_dims)-1-i], activation='relu') (g_dense1)
else:
g_dense = keras.layers.Dense(hidden_dims[len(hidden_dims)-1-i], activation='relu') (g_dense)
if num_hidden_layers > 1:
g_out = keras.layers.Dense(input_dim, activation='linear',name='dec_out') (g_dense)
else:
g_out = keras.layers.Dense(input_dim, activation='linear',name='dec_out') (g_dense1)
model = keras.Model(x_t,g_out,name='ae')
return model
| 10,613 | 35.854167 | 153 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/reconstruction_models/__init__.py | from .vanilla_autoencoder import Autoencoder
__all__ = ['Autoencoder'] | 72 | 17.25 | 44 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/rule_models/anomaly_explanation.py | class AnomalyExplanation(object):
'''
Explanation of reported anomaly
'''
def __init__(self):
'''
Constructor
'''
self._records = {}
self._rule_feats_dict = {}
def add_record(self, feat, location, score, rule, rule_feats):
if self._records.get(feat, None) is None:
self._records[feat] = [(location,score,rule,rule_feats)]
else:
self._records[feat].append( (location,score,rule,rule_feats) )
self._rule_feats_dict[rule] = rule_feats
def summary(self):
"""
get explanation summary
Returns
-------
list of tuples
[(anomalous feature,probability,violated rule,violated locations,related features),...]
"""
feat_score_pairs = []
sum_score = 0
for feat in self._records.keys():
# print('feat',feat)
alarms = self._records[feat]
rule_score = {}
rule_location = {}
score = 0
for alarm in alarms:
# print('alarm',alarm)
score += alarm[1]
if rule_score.get(alarm[2] , None) is None:
rule_score[alarm[2]] = alarm[1]
rule_location[alarm[2]] = [alarm[0]]
else:
rule_score[alarm[2]] = rule_score[alarm[2]] + alarm[1]
rule_location[alarm[2]].append(alarm[0])
# print('score',score)
top_score = 0
for rule in rule_score.keys():
if rule_score[rule] > top_score:
top_score = rule_score[rule]
top_rule = rule
sum_score += score
feat_score_pairs.append( (feat,score,top_rule,rule_location[top_rule],self._rule_feats_dict[top_rule]) )
feat_score_pairs = [(fsp[0],fsp[1]/sum_score,fsp[2],fsp[3],fsp[4]) for fsp in feat_score_pairs]
sorted_feat_score_pairs = sorted(
feat_score_pairs,
key=lambda t: t[1],
reverse=True
)
return sorted_feat_score_pairs
| 2,241 | 31.492754 | 116 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/rule_models/rule.py | # import math
from . import helper
class Rule(object):
'''
An Associative Predicate Rule
Parameters
----------
antec : list
list of predicates in the antecedent set
conseq : list
list of predicates in the consequent set
conf : float in [0,1]
the confidence of the rule
support : float in [0,1]
the support of the rule
'''
def __init__(self, antec, conseq, conf, support):
'''
Constructor
'''
self._antec = antec
self._conseq = conseq
self._conf = conf
self._support = support
self._item_dict = None
def __str__(self):
strRule = ''
for item in self._antec:
strRule += self._item_dict[item] + ' and '
strRule = strRule[0:len(strRule)-5]
strRule += ' ---> '
for item in self._conseq:
strRule += self._item_dict[item] + ' and '
strRule = strRule[0:len(strRule)-5]
# strRule += f', sup {rule[3]:.2f}, conf {rule[2]:.2f}'
return strRule
@property
def antec(self):
return self._antec
@property
def conseq(self):
return self._conseq
@property
def conf(self):
return self._conf
@property
def support(self):
return self._support
def size(self):
"""
get the number of predicates in the rule
Returns
-------
int
the number of predicates
"""
return len(self._antec) + len(self._conseq)
def pset(self):
"""
get the set of predicates in the rule
Returns
-------
frozenset
the set of predicates
"""
return frozenset( set(self._antec) | set(self._conseq) )
def set_itemdict(self,item_dict):
self._item_dict = {}
for item in self.pset():
self._item_dict[item] = item_dict[item]
def extract_feats(self):
antec_feats = []
for item in self._antec:
antec_feats.append( helper.extract_feat_from_predicate(self._item_dict[item]) )
conseq_feats = []
for item in self._conseq:
conseq_feats.append( helper.extract_feat_from_predicate(self._item_dict[item]) )
return antec_feats+conseq_feats
| 2,396 | 25.054348 | 92 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/rule_models/helper.py | import numpy as np
from ...preprocessing.signals import ContinuousSignal
def search_insert_position(vals, val2insert):
pos = None
for i in range(len(vals)):
if val2insert <= vals[i]:
pos = i
if pos is None:
pos = len(vals)
return pos
def reset_cutoffs(cutoffs,df,min_samples):
preserved_cutoffs = {}
for feat in cutoffs.keys():
if len(cutoffs[feat]) == 0:
preserved_cutoffs[feat] = []
continue
value_priority_pairs = cutoffs[feat]
sorted_value_priority_pairs = sorted(
value_priority_pairs,
key=lambda t: [t[1],-t[0]],
reverse=True
)
# print(feat,sorted_value_priority_pairs)
for i in range(len(sorted_value_priority_pairs)):
init_val = sorted_value_priority_pairs[i][0]
if len( df.loc[ df[feat]<init_val,:] ) >= min_samples and len( df.loc[ df[feat]>init_val,:] ) >= min_samples:
sorted_value_priority_pairs = sorted_value_priority_pairs[i:]
break
vals = [pair[0] for pair in sorted_value_priority_pairs]
pair2preserve = [sorted_value_priority_pairs[0]]
val2preserve = []
val2preserve.append(vals[0])
for i in range(1, len(vals)):
pos = search_insert_position(val2preserve, vals[i])
if pos == 0:
if len( df.loc[ (df[feat]>=vals[i]) & (df[feat]<val2preserve[0]),:] ) >= min_samples and \
len( df.loc[ df[feat]<vals[i],:] ) >= min_samples:
val2preserve.insert(0,vals[i])
pair2preserve.append(sorted_value_priority_pairs[i])
elif pos == len(val2preserve):
if len( df.loc[ (df[feat]<vals[i]) & (df[feat]>=val2preserve[-1]),:] ) >= min_samples and \
len( df.loc[ df[feat]>=vals[i],:] ) >= min_samples:
val2preserve.append(vals[i])
pair2preserve.append(sorted_value_priority_pairs[i])
else:
if len( df.loc[ (df[feat]<vals[i]) & (df[feat]>=val2preserve[pos-1]),:] ) >= min_samples and \
len(df.loc[(df[feat] < val2preserve[pos]) & (df[feat] >= vals[i]),:]) >= min_samples:
val2preserve.insert(pos, vals[i])
pair2preserve.append(sorted_value_priority_pairs[i])
preserved_cutoffs[feat] = pair2preserve
return preserved_cutoffs
def extract_cutoffs(dtree,feats):
n_nodes = dtree.node_count
children_left = dtree.children_left
children_right = dtree.children_right
feature = dtree.feature
threshold = dtree.threshold
node_samples = dtree.n_node_samples
impurity = dtree.impurity
N = dtree.n_node_samples[0]
node_depth = np.zeros(shape=n_nodes, dtype=np.int64)
is_leaves = np.zeros(shape=n_nodes, dtype=bool)
stack = [(0, 0)] # start with the root node id (0) and its depth (0)
cutoffs = []
while len(stack) > 0:
# `pop` ensures each node is only visited once
node_id, depth = stack.pop()
node_depth[node_id] = depth
# If the left and right child of a node is not the same we have a split
# node
is_split_node = children_left[node_id] != children_right[node_id]
# If a split node, append left and right children and depth to `stack`
# so we can loop through them
if is_split_node:
stack.append((children_left[node_id], depth + 1))
stack.append((children_right[node_id], depth + 1))
else:
is_leaves[node_id] = True
for i in range(n_nodes):
if is_leaves[i] == False:
c_l, c_r = children_left[i], children_right[i]
N_t, N_t_L, N_t_R = node_samples[i], node_samples[c_l], node_samples[c_r]
imp, imp_l, imp_r = impurity[i], impurity[c_l], impurity[c_r]
impurity_decrease = N_t / N * (imp - N_t_R/N_t*imp_r - N_t_L/N_t*imp_l)
if type(feats) == list:
# print(feature[i])
# print(feat)
cutoffs.append( (feats[feature[i]],threshold[i], impurity_decrease) )
else:
cutoffs.append( (feats,threshold[i], impurity_decrease) )
return cutoffs
def link_rules(rules,max_predicates_per_rule):
L = []
for _ in range(max_predicates_per_rule-1):
L.append([])
for rule in rules:
L[rule.size()-2].append( rule )
link_dict = {}
for i in range(0, len(L)-2):
LPrev = L[i]
LNext = L[i+1]
for shortRule in LPrev:
for largeRule in LNext:
if set(shortRule.antec) == set(largeRule.antec) and set(shortRule.conseq).issubset( set(largeRule.conseq) ):
linked_list = link_dict.get(str(shortRule),[])
linked_list.append(str(largeRule))
link_dict[str(shortRule)] = linked_list
return link_dict
def fuzzy_membership(x,predicate,sigstd):
score = 0
if predicate.find(' or ') != -1:
subitems = predicate.split(' or ')
satisfy = False
for subitem in subitems:
if x[subitem]==1:
satisfy = True
break
if satisfy:
score = 1
else:
score = 0
else:
if predicate.find('<=') != -1:
pos1, pos2 = predicate.find('<='), predicate.rfind('<')
lb = float(predicate[:pos1])
ub = float(predicate[pos2+1:])
feat = predicate[pos1+2:pos2]
if x[feat] >= lb and x[feat] <= ub:
score = 1
elif x[feat] < lb:
score = 1-max(1, (lb-x[feat])/(sigstd[feat]+1e-5) )
elif x[feat] > ub:
score = 1-max(1, (x[feat]-ub)/(sigstd[feat]+1e-5) )
elif predicate.find('<') != -1:
pos = predicate.find('<')
ub = float(predicate[pos+1:])
feat = predicate[:pos]
if x[feat] <= ub:
score = 1
else:
score = 1-max(1, (x[feat]-ub)/(sigstd[feat]+1e-5) )
elif predicate.find('>=') != -1:
pos = predicate.find('>=')
lb = float(predicate[pos+2:])
feat = predicate[:pos]
if x[feat] >= lb:
score = 1
else:
score = 1-max(1, (lb-x[feat])/(sigstd[feat]+1e-5) )
else:
if x[predicate] == 1:
score = 1
else:
score = 0
return score
def parse_predicates(df, item_dict, sigstd):
for item in item_dict.values():
scores = df.apply(fuzzy_membership,axis=1,args=(item,sigstd,))
df[item] = scores
return df
def boundary_anomaly_scoring(x,signal,sigstd):
if isinstance(signal, ContinuousSignal):
lb = min(signal.min_value, signal.mean_value-3*signal.std_value)
ub = max(signal.max_value, signal.mean_value+3*signal.std_value)
feat = signal.name
# print(feat,lb,ub)
if x[feat] >= lb and x[feat] <= ub:
score = 0
elif x[feat] < lb:
score = max(1, (lb-x[feat])/(sigstd[feat]+1e-8) )
elif x[feat] > ub:
score = max(1, (x[feat]-ub)/(sigstd[feat]+1e-8) )
else:
satisfy = False
for entry in signal.get_onehot_feature_names():
if x[entry] == 1:
satisfy = True
break
if satisfy:
score = 0
else:
score = 1
return score
def extract_feat_from_predicate(item):
if item.find(' or ') != -1:
return None
else:
if item.find('<=') != -1:
pos1, pos2 = item.find('<='), item.rfind('<')
feat = item[pos1+2:pos2]
elif item.find('<') != -1:
pos = item.find('<')
feat = item[:pos]
elif item.find('>=') != -1:
pos = item.find('>=')
feat = item[:pos]
else:
pos = item.rfind('=')
feat = item[:pos]
return feat
def boundary_rule(signal):
if isinstance(signal, ContinuousSignal):
lb = min(signal.min_value, signal.mean_value-3*signal.std_value)
ub = max(signal.max_value, signal.mean_value+3*signal.std_value)
strOut = str(lb)+'<='+signal.name+'<='+str(ub)
else:
strOut = signal.name + ' in ' + str(signal.get_onehot_feature_names())
# strOut += ', sup 1, conf 1'
return strOut | 8,594 | 35.574468 | 124 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/rule_models/__init__.py | 0 | 0 | 0 | py | |
InvariantRuleAD | InvariantRuleAD-main/core/model/rule_models/invariant_model.py | from .. import BaseModel,AnomalyDetector
from ...utils import override
import random,pickle
from .rule_mining import RuleMiner
from sklearn.tree import DecisionTreeClassifier,DecisionTreeRegressor
from sklearn.preprocessing import KBinsDiscretizer
from ...preprocessing.signals import ContinuousSignal
import numpy as np
import multiprocessing
from . import helper
from .anomaly_explanation import AnomalyExplanation
from enum import Enum
class PredicateMode(Enum):
UniformBins = 201
KMeansBins = 202
DTImpurity = 203
class InvariantRuleModel(BaseModel,AnomalyDetector):
'''
Invariant rule model for interpretable anomaly detection
Parameters
----------
signals : list
the list of signals the model is dealing with
'''
def __init__(self, signals, mode=PredicateMode.DTImpurity):
self._signals = signals
self._mode = mode
self._cont_feats = []
self._disc_feats = []
self._cont_signals = []
self._disc_signals = []
for signal in self._signals:
if isinstance(signal, ContinuousSignal):
self._cont_feats.append(signal.name)
self._cont_signals.append(signal)
else:
self._disc_feats.extend(signal.get_onehot_feature_names())
self._disc_signals.append(signal)
def _propose_cutoff_values(self,df,min_samples_leaf,nbins=5):
cutoffs = {}
for signal in self._cont_signals:
cutoffs[signal.name] = []
if self._mode == PredicateMode.DTImpurity:
for signal in self._disc_signals:
if len(self._cont_feats) > 0:
onehot_feats = signal.get_onehot_feature_names()
df.loc[:,'tempt_label'] = 0
for i in range(len(onehot_feats)):
df.loc[df[onehot_feats[i]]==1,'tempt_label'] = i
xfeats = list(self._cont_feats)
x = df[xfeats].values
y = df['tempt_label'].values
df.drop(columns='tempt_label',inplace=True)
model = DecisionTreeClassifier(criterion = "entropy",min_samples_leaf=int(min_samples_leaf))
model.fit(x,y)
cut_tuples = helper.extract_cutoffs(model.tree_,xfeats)
for ct in cut_tuples:
cutoffs[ct[0]].append( (ct[1],ct[2]) )
for signal in self._cont_signals:
yfeat = signal.name
xfeats = list(self._cont_feats)
xfeats.remove(yfeat)
x = df[xfeats].values
y = df[yfeat].values
y = (y-signal.mean_value)/signal.std_value
model = DecisionTreeRegressor(min_samples_leaf=int(min_samples_leaf))
model.fit(x,y)
cut_tuples = helper.extract_cutoffs(model.tree_,xfeats)
for ct in cut_tuples:
cutoffs[ct[0]].append( (ct[1],ct[2]) )
else:
if self._mode == PredicateMode.KMeansBins:
kbins = 'kmeans'
elif self._mode == PredicateMode.UniformBins:
kbins = 'uniform'
for signal in self._cont_signals:
y = df[signal.name].values
discretizer = KBinsDiscretizer(n_bins=nbins,encode='ordinal',strategy=kbins)
y = discretizer.fit_transform(np.reshape(y,(-1,1)))
edges = discretizer.bin_edges_[0]
for i in range(1,len(edges)-1):
cutoffs[signal.name].append( (edges[i],1) )
cutoffs = helper.reset_cutoffs(cutoffs,df,min_samples_leaf)
return cutoffs
def train(self, train_df, max_predicates_per_rule=5, gamma=0.7, theta=0.1, ub=0.98, min_conf=1,
max_perdicts4rule_mining = 75, max_times4rule_mining = 5,
set_seed=False, use_multicore=False, verbose=True):
"""
learn invariant rules from data
Parameters
----------
train_df : DataFrame
the training data
max_predicates_per_rule : int
max number of predicates in a generated rule
gamma : float in [0,1]
minimum fraction multiplier for predicate in rule generation, less rules will be generated with a larger value
theta : float in [0,1]
lower bound for the support of a predicate
ub : float in [0,1]
upper bound for the support of a predicate, used only for efficiency purpose
min_conf : float in [0,1]
minimum confidence for a rule
max_perdicts4rule_mining : int
the max number of predicts can be allowed in a rule mining process (in order to speed up mining process)
max_times4rule_mining : int
the max number for the rule mining process, only use for when number of generated predicates is larger than max_perdicts_for_rule_mining
set_seed : Bool
whether set random seed for reproducibility
use_multicore : Bool
whether use multiple cores for parallel computing, if set to True, the number of cores to use equals to max_times4rule_mining
verbose : Bool
whether print progress information during training
Returns
-----------------
AssociativePredicateRules
self
"""
if set_seed:
np.random.seed(123)
random.seed(1234)
self._min_conf = min_conf
self._max_predicates_per_rule = max_predicates_per_rule
min_samples_predicate = int(theta * len(train_df))
df = train_df.copy()
cutoffs = self._propose_cutoff_values(df, min_samples_leaf=min_samples_predicate)
#
for feat in self._cont_feats:
if feat not in cutoffs:
df.drop(columns=feat,inplace=True)
continue
vals2preserve = [val_pri_pair[0] for val_pri_pair in cutoffs[feat]]
vals2preserve.sort()
# print(feat,vals2preserve)
for j in range(len(vals2preserve)):
if j == 0:
new_feat = feat + '<' + str(vals2preserve[j])
df[new_feat] = 0
df.loc[df[feat] < vals2preserve[j], new_feat] = 1
if j > 0:
new_feat = str(vals2preserve[j-1]) + '<=' + feat + '<' + str(vals2preserve[j])
df[new_feat] = 0
df.loc[(df[feat]<vals2preserve[j]) & (df[feat]>=vals2preserve[j-1]), new_feat] = 1
if j == len(vals2preserve)-1:
new_feat = feat + '>=' + str(vals2preserve[j])
df[new_feat] = 0
df.loc[df[feat] >= vals2preserve[j], new_feat] = 1
df.drop(columns=feat,inplace=True)
low_feats = []
for entry in df.columns:
support = len(df.loc[df[entry]==1,:])
if support < min_samples_predicate and entry.find('<') == -1 and entry.find('>') == -1:
low_feats.append( entry )
# print('low_feats',low_feats)
start_index = 0
combine_list = []
for i in range(1,len(low_feats)):
df.loc[:,'tempt'] = 0
for j in range(start_index,i):
df.loc[df[low_feats[j]]==1, 'tempt'] = 1
left_support = len(df.loc[df['tempt']==1,:])
# print(low_feats[i],left_support,min_samples_predicate)
if left_support >= min_samples_predicate:
df.loc[:,'tempt'] = 0
for j in range(i+1,len(low_feats)):
df.loc[df[low_feats[j]]==1, 'tempt'] = 1
right_support = len(df.loc[df['tempt']==1,:])
if right_support >= min_samples_predicate:
combine_list.append(low_feats[start_index:i+1])
start_index = i+1
else:
combine_list.append(low_feats[start_index:])
break
df = df.drop(columns='tempt',errors='ignore')
# print('combine list',combine_list)
for entry2combine in combine_list:
new_feat = entry2combine[0]
for i in range(1,len(entry2combine)):
new_feat += ' or ' + entry2combine[i]
df[new_feat] = 0
for feat in entry2combine:
df.loc[df[feat]==1, new_feat] = 1
df = df.drop(columns=feat)
# print('df shape',df.shape)
for entry in df.columns:
support = len(df.loc[df[entry]==1,:])/len(df)
if support > ub or support < theta:
# if verbose:
# print('drop',entry, len( df.loc[df[entry]==1,:])/len(df) )
df = df.drop(columns=entry)
# else:
# if verbose:
# print('keep',entry, len( df.loc[df[entry]==1,:])/len(df) )
if verbose:
print('number of generated predicates:',df.shape[1])
## start invariant rule mining
rules, self._item_dict = RuleMiner.mine_rules(df, max_len=max_predicates_per_rule, gamma=gamma,
theta=theta,max_perdicts_for_rule_mining = max_perdicts4rule_mining,
min_conf = min_conf,
max_times_for_rule_mining = max_times4rule_mining,
use_multicore=use_multicore,verbose=verbose)
self._rules = sorted(rules, key=lambda t: t.size())
self._rule_linkdict = helper.link_rules(self._rules, max_predicates_per_rule)
if verbose:
print('number of generated rules',len(self._rules)+len(self._signals))
return self
def _update_duplicate_rules(self, rule, dupset):
rules = self._rule_linkdict.get(str(rule),[])
dupset.update(set(rules))
for lr in rules:
self._update_duplicate_rules(str(lr), dupset)
@override
def score_samples(self,df,use_boundary_rules=False, use_cores=1):
"""
Same to the predict method
"""
return self.predict(df,use_boundary_rules, use_cores)
@override
def predict(self,df,use_boundary_rules=False, use_cores=1):
"""
Predict the anomaly scores for data
Parameters
----------
df : DataFrame
the test data
use_boundary_rules : bool
whether use boundary rules
kappa : float in (0,inf)
the scaling factor for the contribution of confidence while computing the anomaly score for a violated rule
use_cores : int, default is 1
number of cores to use
Returns
-------
ndarray
the anomaly scores for each row in df
"""
test_df = df.copy()
sigstd = {}
for signal in self._cont_signals:
sigstd[signal.name] = signal.std_value
test_df = helper.parse_predicates(test_df,self._item_dict,sigstd)
test_df.loc[:,'anomaly_score'] = 0
if use_boundary_rules:
for signal in self._signals:
scores = test_df.apply(helper.boundary_anomaly_scoring,axis=1,args=(signal,sigstd,))
test_df.loc[:,'anomaly_score'] += scores
if use_cores <= 1:
rule2ignore = {}
for rule in self._rules:
rule2ignore[str(rule)] = set()
for i in range(len(self._rules)):
rule = self._rules[i]
ignorelist = rule2ignore[str(rule)]
test_df.loc[:,'antecedent'] = 1
test_df.loc[:,'consequent'] = 0
for item in rule.antec:
test_df.loc[test_df[ self._item_dict[item] ]!=1, 'antecedent'] = 0
for item in rule.conseq:
test_df.loc[:, 'consequent'] += 1-test_df[ self._item_dict[item] ].values
scores4rule = np.multiply(test_df['antecedent'].values,test_df['consequent'].values)*rule.support
scores4rule[list(ignorelist)] = 0
test_df.loc[:,'anomaly_score'] += scores4rule
indices = np.where(scores4rule>0)[0]
# print('indices',indices)
dups = set()
self._update_duplicate_rules(rule, dups)
for dup in dups:
if str(dup) not in rule2ignore.keys():
print(dup)
else:
rule2ignore[str(dup)].update(set(indices))
return test_df.loc[:,'anomaly_score'].values
else:
div_num = len(self._rules)//use_cores
manager = multiprocessing.Manager()
results = manager.list()
jobs = []
rule_clusters = [ [] for i in range(use_cores) ]
rule_dict = {}
for rule in self._rules:
rule_dict[str(rule)] = rule
dup_rules = set()
split_index = 0
for rule in self._rules:
if str(rule) in dup_rules:
continue
rule_clusters[split_index].append(rule)
dups = set()
self._update_duplicate_rules(rule, dups)
for dup in dups:
if dup not in dup_rules:
rule_clusters[split_index].append(rule_dict[dup])
dup_rules.update(dups)
if len(rule_clusters[split_index]) >= div_num and split_index < use_cores-1:
split_index += 1
for i in range(use_cores):
rules = rule_clusters[i]
p = multiprocessing.Process(target=self._parallel_rule_checking, args=(test_df,rules,results))
jobs.append(p)
p.start()
for proc in jobs:
proc.join()
results = np.array(results)
results = np.sum(results,axis=0)
return np.add(results,test_df['anomaly_score'].values)
def _parallel_rule_checking(self,df,rules,results):
test_df = df.copy()
test_df['tempt'] = 0
rule2ignore = {}
for rule in rules:
rule2ignore[str(rule)] = set()
for i in range(len(rules)):
rule = rules[i]
ignorelist = rule2ignore[str(rule)]
test_df.loc[:,'antecedent'] = 1
test_df.loc[:,'consequent'] = 0
for item in rule.antec:
test_df.loc[test_df[ self._item_dict[item] ]!=1, 'antecedent'] = 0
for item in rule.conseq:
test_df.loc[:, 'consequent'] += 1-test_df[ self._item_dict[item] ].values
scores4rule = np.multiply(test_df['antecedent'].values,test_df['consequent'].values)*rule.support
scores4rule[list(ignorelist)] = 0
test_df.loc[:,'tempt'] += scores4rule
indices = np.where(scores4rule>0)[0]
# print('indices',indices)
dups = set()
self._update_duplicate_rules(rule, dups)
for dup in dups:
if str(dup) not in rule2ignore.keys():
rule2ignore[str(dup)] = set(indices)
else:
rule2ignore[str(dup)].update(set(indices))
results.append(test_df.loc[:,'tempt'].values)
def get_anomaly_explanation(self,df,use_boundary_rules=False):
"""
get the explanation for anomalies
Parameters
----------
df : DataFrame
the anomalous data
use_boundary_rules : bool
whether use boundary rules
Returns
-------
AnomalyExplanation
anomaly explanation
"""
test_df = df.copy()
sigstd = {}
for signal in self._cont_signals:
sigstd[signal.name] = signal.std_value
test_df = helper.parse_predicates(test_df,self._item_dict,sigstd)
exp = AnomalyExplanation()
if use_boundary_rules:
for signal in self._signals:
scores = test_df.apply(helper.boundary_anomaly_scoring,axis=1,args=(signal,sigstd,)).to_numpy()
indices = np.where(scores>0)[0]
# print(scores)
# print(indices)
for i in indices:
exp.add_record(signal.name, i, scores[i], helper.boundary_rule(signal),[signal.name])
for i in test_df.index:
# print(i,'/',len(test_df))
dups = set()
for rule in self._rules:
if str(rule) in dups:
continue
antec_satisfy = True
conseq_satisfy = True
for item in rule.antec:
if test_df.loc[i,self._item_dict[item]] != 1:
antec_satisfy = False
break
if antec_satisfy:
for item in rule.conseq:
if test_df.loc[i,self._item_dict[item]] != 1:
conseq_satisfy = False
feat = helper.extract_feat_from_predicate(self._item_dict[item])
score = rule.support*(1-test_df.loc[i,self._item_dict[item]])
if feat is not None:
exp.add_record(feat, i, score, str(rule),rule.extract_feats())
if conseq_satisfy == False:
# print('before update', dups)
self._update_duplicate_rules(rule, dups)
# print('after update', dups)
return exp
def export_rules(self, filepath):
"""
export rules to file
Parameters
----------
filepath : string
the file path
"""
with open(filepath,'w') as myfile:
for signal in self._signals:
myfile.write(helper.boundary_rule(signal) + '\n')
for rule in self._rules:
myfile.write(str(rule) + '\n')
myfile.close()
def get_num_rules(self):
"""
get number of rules
Returns
-------
int
the number of rules
"""
return len(self._rules)+len(self._signals)
def score(self):
pass
@override
def save_model(self,model_path=None, model_id=None):
"""
save the model to files
Parameters
----------
model_path : string, default is None
the target folder whether the model files are saved.
If None, a tempt folder is created
model_id : string, default is None
the id of the model, must be specified when model_path is not None
"""
model_path = super().save_model(model_path, model_id)
pickle.dump(self._rules,open(model_path+'/rules.pkl','wb'))
pickle.dump(self._item_dict,open(model_path+'/item_dict.pkl','wb'))
config_dict = {'max_predicates_per_rule':self._max_predicates_per_rule}
pickle.dump(config_dict,open(model_path+'/config_dict.pkl','wb'))
@override
def load_model(self,model_path=None, model_id=None):
"""
load the model from files
Parameters
----------
model_path : string, default is None
the target folder whether the model files are located
If None, load models from the tempt folder
model_id : string, default is None
the id of the model, must be specified when model_path is not None
Returns
-------
InvariantRuleModel
self
"""
model_path = super().load_model(model_path, model_id)
self._item_dict = pickle.load(open(model_path+'/item_dict.pkl','rb'))
rules = pickle.load(open(model_path+'/rules.pkl','rb'))
self._rules = sorted(rules, key=lambda t: t.size())
config_dict = pickle.load(open(model_path+'/config_dict.pkl','rb'))
self._max_predicates_per_rule = config_dict['max_predicates_per_rule']
self._rule_linkdict = helper.link_rules(self._rules, self._max_predicates_per_rule)
return self
| 21,250 | 38.353704 | 148 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/rule_models/rule_mining/MISTree.py |
from .Element import TreeNode, TableEntry
# the structure of a node (item_name, item_count, child-links, node-link)
def count_items(dataset):
"count items in the dataset."
item_count_dict = {}
for transaction in dataset:
for item in transaction:
if item in item_count_dict:
item_count_dict[item] += 1
else:
item_count_dict[item] = 1
return item_count_dict
def insertTree(item_mis_tuples, root, MIN_freq_item_header_table):
"insert_tree."
node = root
for item_mis_tuple in item_mis_tuples:
item = item_mis_tuple[0]
match = False
for child in node.child_links:
if item == child.item:
match = True
child.updateCount(1)
node = child
break
if match == False:
new_node = TreeNode(item, 1, node, [], None)
node.child_links.append(new_node)
if item not in MIN_freq_item_header_table:
MIN_freq_item_header_table[item] = TableEntry(item, item_mis_tuple[1], new_node)
else:
nodelink = MIN_freq_item_header_table[item].node_link
while nodelink.node_link != None:
nodelink = nodelink.node_link
nodelink.node_link = new_node
node = new_node
def printTree(root):
print(' ')
print('print tree')
print(root)
def printTable(MIN_freq_item_header_table, converted=False):
print( ' ' )
print( 'print MIN_freq_item_header_table' )
if converted == False:
for entry in MIN_freq_item_header_table:
str_tempt = str(entry) + ':' + str(MIN_freq_item_header_table[entry].min_freq)
nodelink = MIN_freq_item_header_table[entry].node_link
while nodelink != None:
str_tempt += '->' + str(nodelink.item)
nodelink = nodelink.node_link
print(str_tempt)
else:
for entry in MIN_freq_item_header_table:
str_tempt = str(entry.item) + ':' + str(entry.min_freq)
nodelink = entry.node_link
while nodelink != None:
str_tempt += '->' + str(nodelink.item)
nodelink = nodelink.node_link
print(str_tempt)
def genMIS_tree(dataset, item_count_dict, min_sup):
root = TreeNode(0,0,None,[],None)
MIN_freq_item_header_table = {}
"Construct tree"
for transaction in dataset:
# print(list(transaction))
item_mis_tuples = []
for item in transaction:
# print(item)
im_tuple = (item, min_sup[item])
item_mis_tuples.append(im_tuple)
# print(item_mis_tuples)
item_mis_tuples.sort(key=lambda tup: (tup[1],tup[0]),reverse=True)
insertTree(item_mis_tuples, root, MIN_freq_item_header_table)
# printTree(root)
# print(MIN_freq_item_header_table)
# printTable(MIN_freq_item_header_table)
"Prune tree"
min_value = 9999999
for item in min_sup:
if min_sup[item] < min_value:
min_value = min_sup[item]
pruning_items = []
for item in item_count_dict:
if item_count_dict[item] < min_value:
pruning_items.append(item)
for item in pruning_items:
node = MIN_freq_item_header_table[item].node_link
while node != None:
node.parent_link.child_links.remove(node)
if len(node.child_links) > 0:
node.parent_link.child_links.extend(node.child_links)
for child in node.child_links:
child.parent_link = node.parent_link
node = node.node_link
del MIN_freq_item_header_table[item]
# printTree(root)
# printTable(MIN_freq_item_header_table)
# print(MIN_freq_item_header_table)
MIN_freq_item_header_dict = MIN_freq_item_header_table
MIN_freq_item_header_table = list(MIN_freq_item_header_table.values())
MIN_freq_item_header_table.sort(key=lambda x: (x.min_freq, x.item))
# printTable(MIN_freq_item_header_table, converted = True)
return root, MIN_freq_item_header_table, min_value, MIN_freq_item_header_dict
# print "Merge trees"
# for entry in MIN_freq_item_header_table:
# node = MIN_freq_item_header_table[entry].node_link
# while node.node_link != None:
# if node.parent_link == node.node_link.parent_link:
# node.parent_link.child_links.remove(node.node_link)
# if n
def insert_prefix_path(prefix_path, root, MIN_freq_item_header_table, min_sup):
node = root
for item_count_tuple in prefix_path:
item = item_count_tuple[0]
count = item_count_tuple[1]
match = False
for child in node.child_links:
if item == child.item:
match = True
child.updateCount(count)
node = child
break
if match == False:
new_node = TreeNode(item, count, node, [], None)
node.child_links.append(new_node)
if item not in MIN_freq_item_header_table:
MIN_freq_item_header_table[item] = TableEntry(item, min_sup[item], new_node)
else:
nodelink = MIN_freq_item_header_table[item].node_link
while nodelink.node_link != None:
nodelink = nodelink.node_link
nodelink.node_link = new_node
node = new_node
def genConditional_MIS_tree(conditional_pattern_base, base_pattern, MIS, min_sup, pattern_count_dict):
root = TreeNode(0,0,None,[],None)
MIN_freq_item_header_table = {}
conditional_frequent_patterns = []
# print "Construct conditional tree for base pattern " + str(base_pattern)
for prefix_path in conditional_pattern_base:
insert_prefix_path(prefix_path, root, MIN_freq_item_header_table, min_sup)
pruning_items = []
for item in MIN_freq_item_header_table:
count = 0
node = MIN_freq_item_header_table[item].node_link
while node != None:
count += node.count
node = node.node_link
if count < MIS:
pruning_items.append(item)
new_pattern = list(base_pattern)
new_pattern.append(item)
pattern_count_dict[frozenset(new_pattern)] = count
# print new_pattern
# print count
else:
new_pattern = list(base_pattern)
new_pattern.append(item)
# print new_pattern
conditional_frequent_patterns.append(new_pattern)
pattern_count_dict[frozenset(new_pattern)] = count
# print new_pattern
# print count
for item in pruning_items:
node = MIN_freq_item_header_table[item].node_link
while node != None:
node.parent_link.child_links.remove(node)
if len(node.child_links) > 0:
node.parent_link.child_links.extend(node.child_links)
for child in node.child_links:
child.parent_link = node.parent_link
node = node.node_link
del MIN_freq_item_header_table[item]
if len(MIN_freq_item_header_table) > 0:
MIN_freq_item_header_table = list(MIN_freq_item_header_table.values())
MIN_freq_item_header_table.sort(key=lambda x: (x.min_freq, x.item))
return root, MIN_freq_item_header_table, conditional_frequent_patterns
def CP_growth(tree, header_table, base_pattern, MIS, min_sup, freq_patterns, pattern_count_dict, max_k):
for entry in header_table:
node = entry.node_link
conditional_pattern_base = []
while node != None:
prefix_tree = []
parent = node.parent_link
while parent.parent_link != None:
prefix_tree.append( (parent.item, node.count) )
parent = parent.parent_link
prefix_tree.reverse()
conditional_pattern_base.append(prefix_tree)
node = node.node_link
# print conditional_pattern_base
new_base_pattern = list(base_pattern)
new_base_pattern.append(entry.item)
new_tree, new_header_table, conditional_frequent_patterns = genConditional_MIS_tree(conditional_pattern_base, new_base_pattern, MIS, min_sup, pattern_count_dict)
# print 'print tree for base pattern ' + str(new_base_pattern)
# printTree(new_tree)
freq_patterns.extend(conditional_frequent_patterns)
if len(new_header_table) > 0 and len(new_base_pattern) < max_k:
CP_growth(new_tree, new_header_table, new_base_pattern, MIS,min_sup,freq_patterns, pattern_count_dict, max_k)
def CFP_growth(root, MIN_freq_item_header_table, min_sup, max_k):
freq_patterns = []
pattern_count_dict = {}
for entry in MIN_freq_item_header_table:
node = entry.node_link
conditional_pattern_base = []
while node != None:
prefix_tree = []
parent = node.parent_link
while parent.parent_link != None:
prefix_tree.append( (parent.item, node.count) )
parent = parent.parent_link
prefix_tree.reverse()
conditional_pattern_base.append(prefix_tree)
node = node.node_link
# print conditional_pattern_base
tree, header_table, conditional_frequent_patterns = genConditional_MIS_tree(conditional_pattern_base, [entry.item], entry.min_freq, min_sup, pattern_count_dict)
# print 'print tree for base pattern ' + str(entry.item)
# printTree(tree)
freq_patterns.extend(conditional_frequent_patterns)
if len(header_table) > 0 and max_k>1:
CP_growth(tree, header_table, [entry.item], entry.min_freq, min_sup, freq_patterns, pattern_count_dict,max_k)
return freq_patterns, pattern_count_dict
| 10,081 | 37.776923 | 170 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/rule_models/rule_mining/RuleMiner.py | from . import MISTree
import pandas as pd
from . import RuleGenerator
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import fpgrowth
from mlxtend.frequent_patterns import association_rules
import multiprocessing
from ..rule import Rule
# import time
def _mining(data,gamma, max_k, theta,min_conf,index_dict):
minSup_dict = {}
min_num = len(data)*theta
for entry in data:
minSup_dict[ index_dict[entry] ] = max( gamma*len(data[data[entry] == 1]), min_num )
data.loc[data[entry]==1, entry] = index_dict[entry]
df_list = data.values.tolist()
dataset = []
for datalist in df_list:
temptlist = filter(lambda a: a != 0, datalist)
numbers = list(temptlist)
dataset.append(numbers)
item_count_dict = MISTree.count_items(dataset)
root, MIN_freq_item_header_table, MIN, MIN_freq_item_header_dict = MISTree.genMIS_tree(dataset, item_count_dict, minSup_dict)
freq_patterns, support_data = MISTree.CFP_growth(root, MIN_freq_item_header_table, minSup_dict, max_k)
L = RuleGenerator.arrangePatterns(freq_patterns, support_data, item_count_dict, max_k, MIN)
rules = RuleGenerator.generateRules(len(data), L, support_data, MIN_freq_item_header_dict, minSup_dict, min_confidence=min_conf)
return rules,freq_patterns,support_data
def _parallel_mining(data,gamma, max_k, theta,min_conf,index_dict,frequent_patterns_all,support_data_all,rules_all):
minSup_dict = {}
min_num = len(data)*theta
for entry in data:
minSup_dict[ index_dict[entry] ] = max( gamma*len(data[data[entry] == 1]), min_num )
data.loc[data[entry]==1, entry] = index_dict[entry]
df_list = data.values.tolist()
dataset = []
for datalist in df_list:
temptlist = filter(lambda a: a != 0, datalist)
numbers = list(temptlist)
dataset.append(numbers)
item_count_dict = MISTree.count_items(dataset)
root, MIN_freq_item_header_table, MIN, MIN_freq_item_header_dict = MISTree.genMIS_tree(dataset, item_count_dict, minSup_dict)
freq_patterns, support_data = MISTree.CFP_growth(root, MIN_freq_item_header_table, minSup_dict, max_k)
L = RuleGenerator.arrangePatterns(freq_patterns, support_data, item_count_dict, max_k, MIN)
rules = RuleGenerator.generateRules(len(data), L, support_data, MIN_freq_item_header_dict, minSup_dict, min_confidence=min_conf)
frequent_patterns_all.extend(freq_patterns)
support_data_all.update(support_data)
rules_all.extend(rules)
def _multi_mine(df,gamma, max_k, theta,min_conf,index_dict,max_perdicts_for_rule_mining, max_times_for_rule_mining,use_multicore,verbose):
if use_multicore:
manager = multiprocessing.Manager()
frequent_patterns_all = manager.list()
support_data_all = manager.dict()
rules_all = manager.list()
jobs = []
for i in range(max_times_for_rule_mining):
if verbose:
print('Start rule ming process:',i+1,"/",max_times_for_rule_mining)
data = df.sample(n=max_perdicts_for_rule_mining,axis='columns')
p = multiprocessing.Process(target=_parallel_mining, args=(data,gamma, max_k, theta,min_conf,index_dict,
frequent_patterns_all,support_data_all,rules_all))
jobs.append(p)
p.start()
for proc in jobs:
proc.join()
else:
frequent_patterns_all = []
support_data_all = {}
rules_all = []
for i in range(max_times_for_rule_mining):
if verbose:
print('Start rule ming process:',i+1,"/",max_times_for_rule_mining)
data = df.sample(n=max_perdicts_for_rule_mining,axis='columns')
rules,freq_patterns,support_data = _mining(data,gamma, max_k, theta,min_conf,index_dict)
frequent_patterns_all.extend(freq_patterns)
support_data_all.update(support_data)
rules_all.extend(rules)
##filter duplicated rules
final_rules = []
rule_dict = {}
for rule in rules_all:
if rule.pset() not in rule_dict.keys():
final_rules.append(rule)
rule_dict[rule.pset()] = [( set(rule.antec),set(rule.conseq) )]
else:
exist_rules = rule_dict[rule.pset()]
for ex_rule in exist_rules:
ant,con = ex_rule
dup = False
if set(ant) == set(rule.antec) or set(con) == set(rule.conseq):
dup = True
break
if not dup:
final_rules.append(rule)
rule_dict[rule.pset()].append( ( set(rule.antec),set(rule.conseq) ) )
return final_rules
def _mining_fp(data, max_len, theta,min_conf,index_dict):
for entry in data:
data.loc[data[entry]==1, entry] = index_dict[entry]
df_list = data.values.tolist()
dataset = []
for datalist in df_list:
temptlist = filter(lambda a: a != 0, datalist)
numbers = list(temptlist)
dataset.append(numbers)
te = TransactionEncoder()
te_ary = te.fit(dataset).transform(dataset)
df = pd.DataFrame(te_ary, columns=te.columns_)
frequent = fpgrowth(df, min_support=theta,use_colnames=True,max_len=int(max_len))
df = association_rules(frequent,metric='confidence',min_threshold=min_conf)
rules = []
for i in range(len(df)):
antecedents = df.loc[i,'antecedents']
consequents = df.loc[i,'consequents']
confidence = df.loc[i,'confidence']
support = df.loc[i,'support']
rule = Rule(antecedents,consequents,confidence,support)
rules.append(rule)
return rules
def mine_rules(df, max_len, gamma, theta, min_conf, max_perdicts_for_rule_mining, max_times_for_rule_mining,use_multicore,verbose):
index_dict = {}
item_dict = {}
index = 100
for entry in df:
index_dict[entry] = index
item_dict[index] = entry
index += 1
if gamma == 0:
data = df.copy()
rules = _mining_fp(data, max_len, theta,min_conf,index_dict)
else:
if df.shape[1] <= max_perdicts_for_rule_mining or max_times_for_rule_mining<=1:
data = df.copy()
rules,_,_ = _mining(data, gamma, max_len-1, theta,min_conf,index_dict)
else:
rules = _multi_mine(df,gamma, max_len-1, theta,min_conf,index_dict,max_perdicts_for_rule_mining, max_times_for_rule_mining,use_multicore,verbose)
for rule in rules:
rule.set_itemdict(item_dict)
return rules, item_dict | 6,684 | 42.69281 | 157 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/rule_models/rule_mining/Element.py | class TreeNode(object):
'''
TreeNode
'''
def __init__(self, item, count, parent_link, child_links, node_link):
'''
Constructor
'''
self.item = item
self.count = count
self.parent_link = parent_link
self.child_links = child_links
self.node_link = node_link
def updateCount(self, num):
self.count += num
def __str__(self, level=0):
ret = "\t"*level+str(self.item)+':'+str(self.count)+"\n"
for child in self.child_links:
ret += child.__str__(level+1)
return ret
class TableEntry(object):
'''
TableEntry
'''
def __init__(self, item, min_freq, node_link):
'''
Constructor
'''
self.item = item
self.min_freq = min_freq
self.node_link = node_link | 860 | 20.525 | 73 | py |
InvariantRuleAD | InvariantRuleAD-main/core/model/rule_models/rule_mining/__init__.py | 0 | 0 | 0 | py | |
InvariantRuleAD | InvariantRuleAD-main/core/model/rule_models/rule_mining/RuleGenerator.py | from ..rule import Rule
def arrangePatterns(freq_patterns, support_data, item_count_dict, max_k, MIN):
"""arrange frequent patterns
"""
L = []
for _ in range(max_k+1):
L.append([])
for item in item_count_dict:
if item_count_dict[item] >= MIN:
key =frozenset([item])
support_data[key] = item_count_dict[item]
L[0].append(key)
for pattern in freq_patterns:
L[len(pattern)-1].append( frozenset(pattern) )
return L
def generateRules(MAX, L, support_data, MIN_freq_item_header_table,min_sup, min_confidence):
"""Create the association rules
L: list of frequent item sets
support_data: support data for those itemsets
min_confidence: minimum confidence threshold
"""
rules = []
for i in range(1, len(L)):
for freqSet in L[i]:
H1 = [frozenset([item]) for item in freqSet]
# print "freqSet", freqSet, 'H1', H1
if (i > 1):
rules_from_conseq(MAX,freqSet, H1, support_data, rules,MIN_freq_item_header_table,min_sup, min_confidence)
else:
calc_confidence(MAX,freqSet, H1, support_data, rules,MIN_freq_item_header_table,min_sup, min_confidence)
return rules
def calculateSupportCount(MIN_freq_item_header_table,itemlist,min_sup):
item_mis_tuples = []
for item in itemlist:
im_tuple = (item, min_sup[item])
item_mis_tuples.append(im_tuple)
item_mis_tuples.sort(key=lambda tup: (tup[1],tup[0]))
count = 0
entry = MIN_freq_item_header_table[ item_mis_tuples[0][0] ]
node = entry.node_link
while node != None:
i=1
parent = node.parent_link
while parent.parent_link != None and i<len(item_mis_tuples):
if parent.item == item_mis_tuples[i][0]:
i+=1
parent = parent.parent_link
# print 'i:' + str(i) + ' len:' + str( len(item_mis_tuples) )
if i == len(item_mis_tuples):
count += node.count
node = node.node_link
return count
def calc_confidence(MAX, freqSet, H, support_data, rules, MIN_freq_item_header_table,min_sup, min_confidence):
"Evaluate the rule generated"
pruned_H = []
for conseq in H:
if freqSet-conseq not in support_data:
itemlist = list(freqSet - conseq)
support_data[freqSet - conseq] = calculateSupportCount(MIN_freq_item_header_table,itemlist,min_sup)
#
# conf = support_data[freqSet] / support_data[freqSet - conseq]
# if conf >= min_confidence:
# rules.append((freqSet - conseq, conseq, conf))
# pruned_H.append(conseq)
# itemlist = list(freqSet)
# count = calculateSupportCount(MIN_freq_item_header_table,itemlist,min_sup)
# if count != support_data[freqSet]:
# print itemlist
# print 'count: ' + str(count) + ' support: ' + str(support_data[freqSet])
#
# itemlist = list(freqSet-conseq)
# count = calculateSupportCount(MIN_freq_item_header_table,itemlist,min_sup)
# if count != support_data[freqSet-conseq]:
# print itemlist
# print 'count: ' + str(count) + ' support: ' + str(support_data[freqSet-conseq])
# if freqSet-conseq in support_data:
conf = support_data[freqSet]*1.0 / support_data[freqSet - conseq]
support = support_data[freqSet]/MAX
if conf >= min_confidence:
# print conf
rules.append( Rule(freqSet - conseq, conseq, conf, support) )
pruned_H.append(conseq)
return pruned_H
def aprioriGen(freq_sets, k):
"Generate the joint transactions from candidate sets"
retList = []
lenLk = len(freq_sets)
for i in range(lenLk):
for j in range(i + 1, lenLk):
L1 = list(freq_sets[i])[:k - 2]
L2 = list(freq_sets[j])[:k - 2]
L1.sort()
L2.sort()
if L1 == L2:
retList.append(freq_sets[i] | freq_sets[j])
return retList
def rules_from_conseq(MAX, freqSet, H, support_data, rules, MIN_freq_item_header_table,min_sup, min_confidence):
"Generate a set of candidate rules"
m = len(H[0])
if (len(freqSet) > (m + 1)):
Hmp1 = aprioriGen(H, m + 1)
Hmp1 = calc_confidence(MAX, freqSet, Hmp1, support_data, rules,MIN_freq_item_header_table,min_sup, min_confidence)
if len(Hmp1) > 1:
rules_from_conseq(MAX, freqSet, Hmp1, support_data, rules,MIN_freq_item_header_table,min_sup, min_confidence) | 4,660 | 37.520661 | 123 | py |
InvariantRuleAD | InvariantRuleAD-main/core/preprocessing/signals.py | class BaseSignal(object):
'''
The base signal class
Parameters
----------
name : string
the name of the signal
isInput : bool
whether it is an input of the model
isOutput : bool
whether it is an output of the model
'''
def __init__(self, name, isInput, isOutput):
self.name = name
self.isInput = isInput
self.isOutput = isOutput
def to_dict(self):
return {'name':self.name, 'isInput':self.isInput, 'isOutput':self.isOutput}
class ContinuousSignal(BaseSignal):
'''
The class for signals which take continuous values
Parameters
----------
name : string
the name of the signal
isInput : bool
whether it is an input of the model
isOutput : bool
whether it is an output of the model
min_value : float, default is None
the minimal value for the signal
max_value : float, default is None
the maximal value for the signal
mean_value : float, default is None
the mean for the signal value distribution
std_value : float, default is None
the std for the signal value distribution
'''
def __init__(self, name, isInput, isOutput, min_value=None, max_value=None, mean_value=None, std_value=None):
'''
Constructor
'''
super().__init__(name, isInput, isOutput)
self.min_value = min_value
self.max_value = max_value
self.mean_value = mean_value
self.std_value = std_value
def to_dict(self):
pdict = super().to_dict()
cdict = {'type':'continuous','min_value':self.min_value,'max_value':self.max_value,'mean_value':self.mean_value,'std_value':self.std_value}
return {**pdict,**cdict}
class CategoricalSignal(BaseSignal):
'''
The class for signals which take discrete values
Parameters
----------
name : string
the name of the signal
isInput : bool
whether it is an input of the model
isOutput : bool
whether it is an output of the model
values : list
the list of possible values for the signal
'''
def __init__(self, name, isInput, isOutput, values):
'''
Constructor
'''
super().__init__(name, isInput, isOutput)
self.values = values
def get_onehot_feature_names(self):
"""
Get the one-hot encoding feature names for the possible values of the signal
Returns
-------
list
the list of one-hot encoding feature names
"""
name_list = []
for value in self.values:
name_list.append(self.name+'='+str(value))
# if len(self.values) > 2:
# for value in self.values:
# name_list.append(self.name+'='+str(value))
# else:
# name_list.append(self.name+'='+str(self.values[0]))
return name_list
def get_feature_name(self,value):
"""
Get the one-hot encoding feature name for a possible value of the signal
Parameters
----------
value : object
A possible value of the signal
Returns
-------
string
the one-hot encoding feature name of the given value
"""
return self.name+'='+str(value)
def to_dict(self):
pdict = super().to_dict()
cdict = {'type':'categorical','values':self.values}
return {**pdict,**cdict}
| 3,594 | 26.868217 | 147 | py |
InvariantRuleAD | InvariantRuleAD-main/core/preprocessing/data_loader.py | import pandas as pd
import numpy as np
from .signals import ContinuousSignal,CategoricalSignal
import zipfile
from enum import Enum
class DATASET(Enum):
SWAT = 101
BATADAL = 102
KDDCup99 = 103
GasPipeline = 104
Annthyroid = 105
Cardio = 106
def load_dataset(ds):
if ds == DATASET.SWAT:
return load_swat_data()
elif ds == DATASET.KDDCup99:
return load_kddcup99_10_percent_data()
elif ds == DATASET.GasPipeline:
return load_gas_data()
elif ds == DATASET.Annthyroid:
return load_annthyroid_data()
elif ds == DATASET.Cardio:
return load_cardio_data()
elif ds == DATASET.BATADAL:
return load_batadal_data()
else:
print('Cannot find the dataset!')
return None
def load_swat_data(fp='../datasets/SWAT'):
"""
load SWAT dataset
Parameters
----------
fp : string, default is '../datasets/SWAT'
the path of the folder where the dataset locates
Returns
-------
Dataframe
the training dataframe
Dataframe
the testing dataframe
ndarray
the test labels
list
the list of signals
"""
z_tr = zipfile.ZipFile(fp+'/SWaT_train.zip', "r")
f_tr = z_tr.open(z_tr.namelist()[0])
train_df=pd.read_csv(f_tr)
f_tr.close()
z_tr.close()
z_tr = zipfile.ZipFile(fp+'/SWaT_test.zip', "r")
f_tr = z_tr.open(z_tr.namelist()[0])
test_df=pd.read_csv(f_tr)
f_tr.close()
z_tr.close()
test_df['label'] = 0
test_df.loc[test_df['Normal/Attack']!='Normal', 'label'] = 1
sensors = ['FIT101','LIT101','AIT201','AIT202','AIT203','FIT201',
'DPIT301','FIT301','LIT301','AIT401','AIT402','FIT401',
'LIT401','AIT501','AIT502','AIT503','AIT504','FIT501',
'FIT502','FIT503','FIT504','PIT501','PIT502','PIT503','FIT601',]
actuators = ['MV101','P101','P102','MV201','P201','P202',
'P203','P204','P205','P206','MV301','MV302',
'MV303','MV304','P301','P302','P401','P402',
'P403','P404','UV401','P501','P502','P601',
'P602','P603']
for sensor in sensors:
train_df['delta_'+sensor] = train_df[sensor].shift(-1)-train_df[sensor]
test_df['delta_'+sensor] = test_df[sensor].shift(-1)-test_df[sensor]
train_df = train_df.dropna()
test_df = test_df.dropna()
signals = []
for name in sensors:
if train_df[name].min() != train_df[name].max():
signals.append( ContinuousSignal(name, isInput=True, isOutput=True,
min_value=train_df[name].min(), max_value=train_df[name].max(),
mean_value=train_df[name].mean(), std_value=train_df[name].std()) )
signals.append( ContinuousSignal('delta_'+name, isInput=True, isOutput=True,
min_value=train_df['delta_'+name].min(), max_value=train_df['delta_'+name].max(),
mean_value=train_df['delta_'+name].mean(), std_value=train_df['delta_'+name].std()) )
for name in actuators:
if len(train_df[name].unique().tolist()) >= 2:
signals.append( CategoricalSignal(name, isInput=True, isOutput=True,
values=train_df[name].unique().tolist()) )
return train_df,test_df,test_df['label'].values,signals
def load_batadal_data(fp='../datasets/BATADAL/'):
"""
load DATADAL dataset
"""
z_tr = zipfile.ZipFile(fp+'/BATADAL_dataset03.zip', "r")
f_tr = z_tr.open(z_tr.namelist()[0])
train_df=pd.read_csv(f_tr)
f_tr.close()
z_tr.close()
z_tr = zipfile.ZipFile(fp+'/BATADAL_dataset04.zip', "r")
f_tr = z_tr.open(z_tr.namelist()[0])
test_df=pd.read_csv(f_tr)
f_tr.close()
z_tr.close()
new_cols = {}
for col in test_df.columns:
new_cols[col]=col.strip()
test_df.rename(columns = new_cols, inplace = True)
test_df['label'] = 0
test_df.loc[test_df['ATT_FLAG'] != -999, 'label'] = 1
signals = []
for name in train_df:
if name!='DATETIME' and name!='ATT_FLAG' and len(train_df[name].unique())>5:
signals.append(ContinuousSignal(name, isInput=True, isOutput=True,
min_value=train_df[name].min(), max_value=train_df[name].max(),
mean_value=train_df[name].mean(), std_value=train_df[name].std()))
elif name!='DATETIME' and name!='ATT_FLAG' and len(train_df[name].unique())<=5:
signals.append( CategoricalSignal(name, isInput=True, isOutput=False,
values=train_df[name].unique().tolist()) )
return train_df, test_df, test_df['label'].values, signals
def load_kddcup99_10_percent_data(fp='../datasets/kddcup99/'):
"""
load kddcup99_10_percent dataset
Parameters
----------
fp : string, default is '../datasets/categorical data/'
the path of the folder where the dataset locates
Returns
-------
Dataframe
the training dataframe
Dataframe
the testing dataframe
ndarray
the test labels
list
the list of signals
-------
"""
z_tr = zipfile.ZipFile(fp+'/kddcup_data_10_percent_normal_train.zip', "r")
f_tr = z_tr.open(z_tr.namelist()[0])
train_df=pd.read_csv(f_tr)
f_tr.close()
z_tr.close()
z_tr = zipfile.ZipFile(fp+'/kddcup_data_10_percent_test.zip', "r")
f_tr = z_tr.open(z_tr.namelist()[0])
test_df=pd.read_csv(f_tr)
f_tr.close()
z_tr.close()
test_df['label'] = 0
test_df.loc[test_df['Normal/Attack'] != 'normal.', 'label'] = 1
pos_df = test_df.loc[test_df['label']==0,:]
neg_df = test_df.loc[test_df['label']==1,:]
neg_df = neg_df.sample(n=len(pos_df)//4)
test_df = pd.concat([pos_df,neg_df])
test_df = test_df.reset_index()
sensors = ['duration', 'src_bytes', 'dst_bytes', 'wrong_fragment', 'urgent', 'hot',
'num_failed_logins', 'num_compromised', 'root_shell', 'su_attempted', 'num_root', 'num_file_creations',
'num_shells', 'num_access_files', 'num_outbound_cmds', 'count', 'srv_count', 'serror_rate',
'srv_serror_rate', 'rerror_rate', 'srv_rerror_rate', 'same_srv_rate', 'diff_srv_rate', 'srv_diff_host_rate', 'dst_host_count',
'dst_host_srv_count', 'dst_host_same_srv_rate','dst_host_diff_srv_rate','dst_host_same_src_port_rate',
'dst_host_srv_diff_host_rate','dst_host_serror_rate','dst_host_srv_serror_rate','dst_host_rerror_rate', 'dst_host_srv_rerror_rate',]
actuators = ['protocol_type','service','flag','land','logged_in','is_host_login','is_guest_login',]
signals = []
for name in sensors:
if train_df[name].min() != train_df[name].max():
signals.append(ContinuousSignal(name, isInput=True, isOutput=True,
min_value=train_df[name].min(), max_value=train_df[name].max(),
mean_value=train_df[name].mean(), std_value=train_df[name].std()))
for name in actuators:
# train_df.loc[train_df[name]==2,name]=3
# test_df.loc[test_df[name]==2,name]=3
if len(train_df[name].unique().tolist()) >= 2:
signals.append(CategoricalSignal(name, isInput=True, isOutput=False,
values=train_df[name].unique().tolist()))
# elif len(train_df[name].unique().tolist()) == 2:
# signals.append( BinarySignal(name, SignalSource.controller, isInput=True, isOutput=False,
# values=train_df[name].unique().tolist()) )
return train_df.loc[:, sensors + actuators], test_df.loc[:, sensors + actuators], test_df['label'].values, signals
def load_gas_data(fp='../datasets/'):
z_tr = zipfile.ZipFile(fp+'/IanArffDataset.zip', "r")
f_tr = z_tr.open(z_tr.namelist()[0])
df=pd.read_csv(f_tr)
f_tr.close()
z_tr.close()
df = df.replace('?',np.nan)
df = df.fillna(method='ffill')
df = df.apply(pd.to_numeric)
df['interval'] = df['time'].shift(-1)-df['time']
df = df.dropna()
df.drop(['specific result','categorized result','time'], axis = 1, inplace = True)
pos = len(df)*3//5
train_df = df.loc[:pos,:].reset_index(drop=True)
train_df = train_df.loc[train_df['binary result']==0,:].reset_index(drop=True)
test_df = df.loc[pos:,:].reset_index(drop=True)
pos_df = test_df.loc[test_df['binary result']==0,:]
neg_df = test_df.loc[test_df['binary result']==1,:]
neg_df = neg_df.sample(n=len(pos_df)//4)
test_df = pd.concat([pos_df,neg_df])
signals = []
for name in train_df:
if name not in ['binary result',] and len(train_df[name].unique())>5:
signals.append( ContinuousSignal(name, isInput=True, isOutput=True,
min_value=train_df[name].min(), max_value=train_df[name].max(),
mean_value=train_df[name].mean(), std_value=train_df[name].std() ) )
elif name not in ['binary result',] and len(train_df[name].unique())<=5:
signals.append( CategoricalSignal(name, isInput=True, isOutput=False,
values=train_df[name].unique().tolist()) )
return train_df,test_df,test_df['binary result'].values,signals
def load_annthyroid_data(fp='../datasets/'):
"""
load annthyroid dataset
"""
df = pd.read_csv(fp+'annthyroid_21feat_normalised.csv')
pos = len(df)*3//5
train_df = df.loc[:pos,:].reset_index(drop=True)
train_df = train_df.loc[df['class']==0,:].reset_index(drop=True)
test_df = df.loc[pos:,:].reset_index(drop=True)
signals = []
for name in train_df:
if name!='class' and len(train_df[name].unique())>5:
signals.append( ContinuousSignal(name, isInput=True, isOutput=True,
min_value=train_df[name].min(), max_value=train_df[name].max(),
mean_value=train_df[name].mean(), std_value=train_df[name].std() ) )
elif name!='class' and len(train_df[name].unique())<=5:
signals.append( CategoricalSignal(name, isInput=True, isOutput=False,
values=train_df[name].unique().tolist()) )
return train_df,test_df,test_df['class'].values,signals
def load_cardio_data():
"""
load npz dataset
"""
data = np.load('../datasets/cardio.npz', allow_pickle=True)
X = data['X']
y = data['y']
cols = []
for i in range(X.shape[1]):
cols.append('col'+str(i))
df = pd.DataFrame(data=X,columns=cols)
df['class'] = y
pos = len(df)*3//5
train_df = df.loc[:pos,:].reset_index(drop=True)
train_df = train_df.loc[df['class']==0,:].reset_index(drop=True)
test_df = df.loc[pos:,:].reset_index(drop=True)
pos_df = test_df.loc[test_df['class']==0,:]
neg_df = test_df.loc[test_df['class']==1,:]
if len(neg_df) > len(pos_df)//4:
neg_df = neg_df.sample(n=len(pos_df)//4)
test_df = pd.concat([pos_df,neg_df])
signals = []
for name in train_df:
if name!='class' and len(train_df[name].unique())>5:
signals.append( ContinuousSignal(name, isInput=True, isOutput=True,
min_value=train_df[name].min(), max_value=train_df[name].max(),
mean_value=train_df[name].mean(), std_value=train_df[name].std() ) )
elif name!='class' and len(train_df[name].unique())<=5:
signals.append( CategoricalSignal(name, isInput=True, isOutput=False,
values=train_df[name].unique().tolist()) )
return train_df,test_df,test_df['class'].values,signals
| 12,294 | 36.484756 | 147 | py |
InvariantRuleAD | InvariantRuleAD-main/core/preprocessing/data_util.py | from .signals import CategoricalSignal,ContinuousSignal
import json
import warnings
def signals2dfcolumns(signals):
"""
get df column names given signals
Parameters
----------
signals : list
the list of signals
Returns
-------
list of strings
the dataframe column names
"""
cols = []
for signal in signals:
if isinstance(signal, CategoricalSignal):
cols.extend(signal.get_onehot_feature_names())
if isinstance(signal, ContinuousSignal):
cols.append(signal.name)
return cols
class DataUtil():
'''
Utility class for data normalization, denormalization and onehot encoding
Parameters
----------
signals : list, default is None
the list of signals, must be specified when filename is None
scaling method : {None,"min_max","standard"}, default is None
scaler=None indicates no normalization;
scaler="min_max" indicates using MinMax scaling;
scaler="standard" indicates using standard scaling;
filename : string, default is None
the path of json file to load DataUtil, must be specified when signals is None
'''
def __init__(self, signals=None, scaling_method=None, filename=None):
if filename is None:
self.signals = signals
self.scaling_method = scaling_method
else:
self._load_jsonfile(filename)
self.signal_map = {signal.name: signal for signal in self.signals}
def normalize_and_encode(self, df):
"""
Normalize and onehot encode the signals in the dataset
Parameters
----------
df : DataFrame
The dataset
Returns
-------
Dataframe
the modified dataframe
"""
df = df.copy()
#'onehot encoding and normalisation'
for signal in self.signals:
if isinstance(signal, CategoricalSignal):
for value in signal.values:
new_entry = signal.get_feature_name(value)
df.loc[:,new_entry] = 0
df.loc[df[signal.name]==value,new_entry] = 1
if isinstance(signal, ContinuousSignal):
df[signal.name] = df[signal.name].astype(float)
if self.scaling_method == 'min_max':
if signal.max_value is None or signal.min_value is None:
msg = 'please specify min max values for signal' + signal.name
warnings.warn(msg)
if signal.max_value != signal.min_value:
df[signal.name]= df[signal.name].apply(lambda x:float(x-signal.min_value)/float(signal.max_value-signal.min_value))
else:
msg = signal.name + ' has no variation, consider remove this signal!'
warnings.warn(msg)
elif self.scaling_method == 'standard':
if signal.mean_value is None or signal.std_value is None:
msg = 'please specify mean and std values for signal' + signal.name
warnings.warn(msg)
if signal.std_value != 0:
df[signal.name]=df[signal.name].apply(lambda x:float(x-signal.mean_value)/float(signal.std_value))
else:
msg = signal.name + ' has no variation, consider remove this signal!'
warnings.warn(msg)
df = df[signals2dfcolumns(self.signals)]
return df
def onehot_encode(self, df):
"""
onehot encode the signals in the dataset
Parameters
----------
df : DataFrame
The dataset
Returns
-------
Dataframe
the modified dataframe
"""
df = df.copy()
#'onehot encoding'
cols = []
for signal in self.signals:
if isinstance(signal, CategoricalSignal):
for value in signal.values:
new_entry = signal.get_feature_name(value)
df[new_entry] = 0
df.loc[df[signal.name]==value,new_entry] = 1
cols.append(new_entry)
if isinstance(signal, ContinuousSignal):
cols.append(signal.name)
df = df[cols]
return df
def denormalize(self,data,cols):
"""
Denormalize the data according to its column names
Parameters
----------
data : ndarray
The data, must be matrix of shape = [n_samples, n_cols]
cols : list of strings
The column names, each column name must be the name of a signal
Returns
-------
ndarray
The denormalized data
"""
data = data.copy()
for i in range(len(cols)):
signal = self.signal_map[cols[i]]
if self.scaling_method == 'min_max':
if signal.min_value != signal.max_value:
data[:,i] = (signal.max_value-signal.min_value)*data[:,i]+signal.min_value
elif self.scaling_method == 'standard':
if signal.std_value != 0:
data[:,i] = data[:,i]*float(signal.std_value)+signal.mean_value
return data
def save2jsonfile(self,filename):
"""
save to a Json file
Parameters
----------
filename : string
the path of json file to save DataUtil
"""
ret = {'scaling_method':self.scaling_method}
ret['signals'] = []
for signal in self.signals:
ret['signals'].append(signal.to_dict())
with open(filename, 'w') as outfile:
json.dump(ret,outfile)
def _load_jsonfile(self,filename):
with open(filename, 'r') as inputfile:
data = inputfile.read()
configJson = json.loads(data)
self.scaling_method = configJson['scaling_method']
self.signals = []
for sd in configJson['signals']:
if sd['type'] == 'continuous':
signal = ContinuousSignal(sd['name'],isInput=sd['isInput'],isOutput=sd['isOutput'],
min_value=sd['min_value'],max_value=sd['max_value'],
mean_value=sd['mean_value'],std_value=sd['std_value'])
elif sd['type'] == 'categorical':
signal = CategoricalSignal(sd['name'],isInput=sd['isInput'],isOutput=sd['isOutput'],
values=sd['values'])
self.signals.append(signal)
| 6,930 | 34.54359 | 139 | py |
InvariantRuleAD | InvariantRuleAD-main/core/preprocessing/__init__.py | from .data_util import DataUtil
__all__ = ['DataUtil']
def train_val_split(df,val_ratio):
"""
split the dataframe into a train part and a validation part
Parameters
----------
df : DataFrame
The dataset
val_ratio : float
the proportion of the validation part
Returns
-------
Dataframe
the training dataframe
Dataframe
the validation dataframe
"""
pos = int(len(df)*(1-val_ratio))
val_df = df.loc[pos:,:]
val_df = val_df.reset_index(drop=True)
train_df = df.loc[:pos,:]
train_df = train_df.reset_index(drop=True)
return train_df,val_df | 652 | 22.321429 | 63 | py |
InvariantRuleAD | InvariantRuleAD-main/core/preprocessing/data_handler.py | import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import warnings
from builtins import isinstance
class TSAEDataHandler():
'''
Data Handler for time-series autoencoders
Parameters
----------
sequence_length : int
the length of sequence
feats : list of strings
the target variables
df_columns : list of strings
the column names in the DataFrame from where the data is extracted
'''
def __init__(self, sequence_length,feats,df_columns):
# Store the raw data.
self.df_columns = df_columns
self.column_indices = {name: i for i, name in enumerate(df_columns)}
self.feats = feats
self.feat_indices = [self.column_indices[name] for name in feats]
# Work out the window parameters.
self.total_window_size = sequence_length
self.feat_index_dict = {name: i for i, name in enumerate(feats)}
def _split_window_for_seq2seq_train(self, features):
inputs = features
inputs = tf.stack([inputs[:, :, idx] for idx in self.feat_indices],axis=-1)
inputs.set_shape([None, self.total_window_size, len(self.feats)])
outputs = tf.reverse(inputs,[1])
return inputs, outputs
def _split_window_for_block_train(self, features):
inputs = features
inputs = tf.stack([inputs[:, :, idx] for idx in self.feat_indices],axis=-1)
inputs = tf.reshape(inputs,[-1,self.total_window_size*len(self.feats)])
return inputs, inputs
def _split_window_for_seq2seq_predict(self, features):
inputs = features
inputs = tf.stack([inputs[:, :, idx] for idx in self.feat_indices],axis=-1)
inputs.set_shape([None, self.total_window_size, len(self.feats)])
return inputs
def _split_window_for_block_predict(self, features):
inputs = features
inputs = tf.stack([inputs[:, :, idx] for idx in self.feat_indices],axis=-1)
inputs = tf.reshape(inputs,[-1,self.total_window_size*len(self.feats)])
return inputs
def _split_window_for_label(self, features):
return features
def make_dataset(self, data, mode, batch_size=256):
"""
make a tensorflow dataset object for model training and validation
Parameters
----------
data : ndarray or list of ndarray
the numpy array from where the samples are extracted
mode : {'seq2seq','block'}
the mode for time-series
batch_size : int
the batch_size
Returns
-------
Dataset
a tf.data.Dataset object
"""
if isinstance(data,list):
cds = None
for dt in data:
dt = np.array(dt, dtype=np.float32)
ds = tf.keras.preprocessing.timeseries_dataset_from_array(
data=dt,
targets=None,
sequence_length=self.total_window_size,
sequence_stride=1,
shuffle=True,
batch_size=batch_size,)
if mode == 'seq2seq':
ds = ds.map(self._split_window_for_seq2seq_train)
elif mode == 'block':
ds = ds.map(self._split_window_for_block_train)
if cds is None:
cds = ds
else:
cds = cds.concatenate(ds)
return cds
else:
data = np.array(data, dtype=np.float32)
ds = tf.keras.preprocessing.timeseries_dataset_from_array(
data=data,
targets=None,
sequence_length=self.total_window_size,
sequence_stride=1,
shuffle=True,
batch_size=batch_size,)
if mode == 'seq2seq':
ds = ds.map(self._split_window_for_seq2seq_train)
elif mode == 'block':
ds = ds.map(self._split_window_for_block_train)
return ds
def extract_data4AD(self, data, mode, stride):
"""
extract input samples as well as output samples from raw data for anomaly detection
Parameters
----------
data : ndarray
the numpy array from where the samples are extracted
mode : {'seq2seq','block'}
the mode for time-series
stride : int
period between successive extracted sequences
Returns
-------
ndarray
the encoder inputs, matrix of shape = [n_samples, n_input_feats]
ndarray
the output data, shape = [n_samples, n_output_feats]
"""
data = np.array(data, dtype=np.float32)
ds = tf.keras.preprocessing.timeseries_dataset_from_array(
data=data,
targets=None,
sequence_length=self.total_window_size,
sequence_stride=stride,
shuffle=False,
batch_size=1,)
if mode == 'seq2seq':
ds = ds.map(self._split_window_for_seq2seq_train)
elif mode == 'block':
ds = ds.map(self._split_window_for_block_train)
x_list, y_list = [], []
for x, y in ds.as_numpy_iterator():
x_list.append(x)
y_list.append(y)
x, y = np.concatenate(x_list), np.concatenate(y_list)
return x, y
def extract_data4predict(self, data, mode, stride):
"""
extract input samples as well as output samples from raw data for ts prediction
Parameters
----------
data : ndarray
the numpy array from where the samples are extracted
mode : {'seq2seq','block'}
the mode for time-series
stride : int
period between successive extracted sequences
Returns
-------
ndarray
the encoder inputs, matrix of shape = [n_samples, n_input_feats]
"""
data = np.array(data, dtype=np.float32)
ds = tf.keras.preprocessing.timeseries_dataset_from_array(
data=data,
targets=None,
sequence_length=self.total_window_size,
sequence_stride=stride,
shuffle=False,
batch_size=1,)
if mode == 'seq2seq':
ds = ds.map(self._split_window_for_seq2seq_predict)
elif mode == 'block':
ds = ds.map(self._split_window_for_block_predict)
x_list = []
for x in ds.as_numpy_iterator():
x_list.append(x)
x = np.concatenate(x_list)
return x
def extract_labels(self, data):
"""
extract labels from raw data
Parameters
----------
data : ndarray
the numpy array from where the labels are extracted
Returns
-------
ndarray
the labels, matrix of shape = [n_samples, output_width]
"""
data = np.array(data, dtype=np.float32)
ds = tf.keras.preprocessing.timeseries_dataset_from_array(
data=data,
targets=None,
sequence_length=self.total_window_size,
sequence_stride=self.total_window_size,
shuffle=False,
batch_size=1,)
ds = ds.map(self._split_window_for_label)
x_list = []
for x in ds.as_numpy_iterator():
x_list.append(x)
labels = np.concatenate(x_list)
labels = labels.sum(axis=1)
labels[labels>0]=1
return labels
def extractRes(self,obs_x,recon_x, target_vars=None,denormalizer=None):
"""
extract prediction compared with inputs
Parameters
----------
obs_x : ndarray
the ground truth data, matrix of shape = [n_samples, n_features]
recon_x : ndarray
the reconstructed data, matrix of shape = [n_samples, n_features]
target_vars : list of string, default is None
the variables to extract, if None, all feats will be extracted
denormalizer: DataUtil, default is None
the DataUtil object to denormalize the data before extraction. If None, no denormalization will be conducted
Returns
-------
ndarray
the extracted ground truth data, matrix of shape = [n_samples, n_target_vars]
ndarray
the extracted reconstructed data, matrix of shape = [n_samples, n_target_vars]
"""
if target_vars is None:
target_vars = self.feats
else:
for var in target_vars:
if var not in self.feats:
msg = 'Warning, ' + var + ' is not a target feature!'
warnings.warn(msg)
return None
if denormalizer is not None:
obs_x = denormalizer.denormalize(obs_x,self.feats)
recon_x = denormalizer.denormalize(recon_x,self.feats)
target_indices = []
for target_var in target_vars:
j = self.feat_index_dict[target_var]
target_indices.append(j)
return obs_x[:,target_indices], recon_x[:,target_indices]
def plotRes(self,obs_x,recon_x,plot_vars=None,denormalizer=None):
"""
plot prediction compared with inputs
Parameters
----------
obs_x : ndarray
the ground truth data, matrix of shape = [n_samples, n_features]
recon_x : ndarray
the reconstructed data, matrix of shape = [n_samples, n_features]
plot_vars : list of string, default is None
the variables to plot, if None, all feats will be plotted
denormalizer: DataUtil, default is None
the DataUtil object to denormalize the data before plot. If None, no denormalization will be conducted
"""
if plot_vars is None:
plot_vars = self.feats
else:
for var in plot_vars:
if var not in self.feats:
msg = 'Warning, ' + var + ' is not a target feature!'
warnings.warn(msg)
return None
if denormalizer is not None:
obs_x = denormalizer.denormalize(obs_x,self.feats)
recon_x = denormalizer.denormalize(recon_x,self.feats)
timeline = np.linspace(0,len(obs_x),len(obs_x))
colors = ['r','g','b','c','m','y']
plt.figure(1)
k=0
for target_var in plot_vars:
j = self.feat_index_dict[target_var]
plt.subplot(len(plot_vars),1,k+1)
plt.plot(timeline,obs_x[:,j],colors[j%6]+"-",label=target_var)
plt.plot(timeline, recon_x[:,j], "k-",label='reconstructed')
plt.legend(loc='best', prop={'size': 6})
k+=1
plt.show()
| 11,215 | 34.381703 | 120 | py |
InvariantRuleAD | InvariantRuleAD-main/experiments/main_if.py | import sys,getopt
sys.path.insert(0, "../")
from core.preprocessing.data_loader import load_dataset,DATASET
from sklearn.ensemble import IsolationForest
from core.preprocessing import DataUtil
from sklearn.metrics import roc_auc_score
if __name__ == "__main__":
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "d:",["dataset="])
except:
print(u'python main_if.py --dataset <dataset>')
sys.exit(2)
ds = None
gamma = None
theta = None
load_saved = False
for opt, arg in opts:
if opt in ['-d','--dataset']:
if arg.lower() == 'swat':
ds = DATASET.SWAT
elif arg.lower() == 'batadal':
ds = DATASET.BATADAL
elif arg.lower() == 'kddcup99':
ds = DATASET.KDDCup99
elif arg.lower() == 'gaspipeline':
ds = DATASET.GasPipeline
elif arg.lower() == 'annthyroid':
ds = DATASET.Annthyroid
elif arg.lower() == 'cardio':
ds = DATASET.Cardio
else:
print(u'python main_if.py --dataset <dataset>')
sys.exit(2)
if ds is None:
print(u'please specify dataset!')
sys.exit(2)
print(ds)
train_df,test_df,test_label,signals = load_dataset(ds)
du = DataUtil(signals,scaling_method='None')
train_df = du.normalize_and_encode(train_df)
test_df = du.normalize_and_encode(test_df)
model = IsolationForest(random_state=5)
model.fit(train_df.values)
true_labels = test_label
scores = model.score_samples(test_df.values)
scores = scores*-1
auc_roc = roc_auc_score(true_labels,scores)
pauc = roc_auc_score(true_labels,scores,max_fpr=0.1)
print('auc',auc_roc)
print('pauc',pauc)
print() | 1,862 | 27.661538 | 63 | py |
InvariantRuleAD | InvariantRuleAD-main/experiments/main_ir.py | import sys,getopt
sys.path.insert(0, "../")
from core.preprocessing.data_loader import load_dataset,DATASET
from core.preprocessing import DataUtil
from core.model.rule_models.invariant_model import InvariantRuleModel,PredicateMode
from sklearn.metrics import roc_auc_score
from core.preprocessing.signals import ContinuousSignal
import json
import numpy as np
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NpEncoder, self).default(obj)
if __name__ == "__main__":
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "d:m:t:g:r",["dataset=","mode=","theta=","gamma=","reproduce"])
except:
print(u'python main_ir.py --dataset <dataset> --mode <mode> --theta <theta> --gamma <gamma> --reproduce')
sys.exit(2)
ds = None
gamma = None
theta = None
load_saved = False
mode = PredicateMode.DTImpurity
for opt, arg in opts:
if opt in ['-d','--dataset']:
if arg.lower() == 'swat':
ds = DATASET.SWAT
elif arg.lower() == 'batadal':
ds = DATASET.BATADAL
elif arg.lower() == 'kddcup99':
ds = DATASET.KDDCup99
elif arg.lower() == 'gaspipeline':
ds = DATASET.GasPipeline
elif arg.lower() == 'annthyroid':
ds = DATASET.Annthyroid
elif arg.lower() == 'cardio':
ds = DATASET.Cardio
elif opt in ['-m','--mode']:
if arg.lower() == 'uniformbins':
mode = PredicateMode.UniformBins
elif arg.lower() == 'kmeansbins':
mode = PredicateMode.KMeansBins
elif arg.lower() == 'dtimpurity':
mode = PredicateMode.DTImpurity
else:
print(u'please specify right mode')
sys.exit(2)
elif opt in ['-t','--theta']:
theta = float(arg)
elif opt in ['-g','--gamma']:
gamma = float(arg)
elif opt in ['-r','--reproduce']:
load_saved = True
else:
print(u'python main_ir.py --dataset <dataset> --mode <mode> --theta <theta> --gamma <gamma> --reproduce')
sys.exit(2)
if ds is None:
print(u'please specify dataset!')
sys.exit(2)
if load_saved == False:
if theta is None or gamma is None:
print(u'please specify theta and gamma!')
sys.exit(2)
print(ds)
train_df,test_df,test_labels,signals = load_dataset(ds)
print('train size',len(train_df))
print('test size',len(test_df))
num_cont, num_cate = 0, 0
for signal in signals:
if isinstance(signal, ContinuousSignal):
num_cont += 1
else:
num_cate += 1
print(f'number of continuous signals: {num_cont}')
print(f'number of categorical signals: {num_cate}')
print('anomaly ratio:',list(test_labels).count(1)/len(test_labels))
du = DataUtil(signals,scaling_method=None)
train_df = du.normalize_and_encode(train_df)
test_df = du.normalize_and_encode(test_df)
irm = InvariantRuleModel(signals,mode)
if load_saved == False:
irm.train(train_df, max_predicates_per_rule=5, gamma=gamma, theta=theta,use_multicore=True)
# irm.save_model('../results/'+str(mode), str(ds))
else:
irm.load_model('../results/'+str(mode), str(ds))
num_rules = irm.get_num_rules()
print('num rules',num_rules)
anomaly_scores = irm.predict(test_df,use_boundary_rules=True,use_cores=1)
auc = roc_auc_score(test_labels[:len(anomaly_scores)],anomaly_scores)
pauc = roc_auc_score(test_labels[:len(anomaly_scores)],anomaly_scores,max_fpr=0.1)
print('AUC',auc)
print('pAUC',pauc)
print()
# if ds == DATASET.SWAT:
# print('---check violated rules for anomaly segments in SWAT---')
# segments = []
# for i in range(1,len(test_labels)):
# if test_labels[i] == 1 and test_labels[i-1] == 0:
# sidx = i
# if test_labels[i] == 0 and test_labels[i-1] == 1:
# segments.append((sidx,i-1))
# print('num segs',len(segments))
# print(segments)
#
# ret_json = {}
# ret_json['abnormal_segments'] = []
# for seg in segments:
# print(seg)
# seg_dict = {'start_index':seg[0], 'end_index':seg[1]}
# anomaly_df = test_df.loc[seg[0]:seg[1]+1,:]
# exp = irm.get_anomaly_explanation(anomaly_df, use_boundary_rules=True)
# causes = []
# for exp_item in exp.summary():
# causes.append( {'feature':exp_item[0],'probability':exp_item[1],'violated_rule':exp_item[2],'involved_features':exp_item[4],'violated_locations':exp_item[3]} )
# seg_dict['causes'] = causes
# ret_json['abnormal_segments'].append(seg_dict)
# # print(exp.summary())
# # print()
# with open("../results/abnormal_segments.json", "w") as outfile:
# json.dump(ret_json, outfile,cls=NpEncoder)
# print('violated rules saved in ../results/abnormal_segments.json')
| 5,500 | 35.919463 | 178 | py |
InvariantRuleAD | InvariantRuleAD-main/experiments/main_ae.py | import sys,getopt
sys.path.insert(0, "../")
from core.model.reconstruction_models import Autoencoder
from core.preprocessing.data_loader import DATASET,load_dataset
from core.learning.hp_optimization.Hyperparameter import UniformIntegerHyperparameter,ConstHyperparameter,CategoricalHyperparameter
from core.learning.hp_optimization import HPOptimizers
from core.preprocessing import DataUtil
from core.preprocessing import train_val_split
from sklearn.metrics import roc_auc_score
if __name__ == "__main__":
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "d:",["dataset="])
except:
print(u'python main_ae.py --dataset <dataset>')
sys.exit(2)
ds = None
gamma = None
theta = None
load_saved = False
for opt, arg in opts:
if opt in ['-d','--dataset']:
if arg.lower() == 'swat':
ds = DATASET.SWAT
elif arg.lower() == 'batadal':
ds = DATASET.BATADAL
elif arg.lower() == 'kddcup99':
ds = DATASET.KDDCup99
elif arg.lower() == 'gaspipeline':
ds = DATASET.GasPipeline
elif arg.lower() == 'annthyroid':
ds = DATASET.Annthyroid
elif arg.lower() == 'cardio':
ds = DATASET.Cardio
else:
print(u'python main_ae.py --dataset <dataset>')
sys.exit(2)
if ds is None:
print(u'please specify dataset!')
sys.exit(2)
print(ds)
train_df,test_df,test_label,signals = load_dataset(ds)
data_util = DataUtil(signals,scaling_method='min_max')
train_df = data_util.normalize_and_encode(train_df)
test_df = data_util.normalize_and_encode(test_df)
train_df, val_df = train_val_split(train_df,val_ratio=0.2)
hidden_dim = len(signals)//4
hp_list = []
hp_list.append(ConstHyperparameter('hidden_dim',hidden_dim))
hp_list.append(UniformIntegerHyperparameter('num_hidden_layers',1,3))
hp_list.append(ConstHyperparameter('save_best_only',True))
hp_list.append(UniformIntegerHyperparameter('epochs',50,100))
hp_list.append(ConstHyperparameter('verbose',2))
hp_list.append(CategoricalHyperparameter('batch_size',[64,256]))
model = Autoencoder(signals)
optor = HPOptimizers.RandomizedGridSearch(model, hp_list,train_df.values, val_df.values)
optModel,optHPCfg,bestScore = optor.run(n_searches=2,verbose=0)
# print('optHPCfg',optHPCfg)
# print('bestScore',bestScore)
scores = optModel.score_samples(test_df.values,return_evidence=False)
labels = optModel.data_handler.extract_labels(test_label)
auc_roc = roc_auc_score(labels,scores)
pauc = roc_auc_score(labels,scores,max_fpr=0.1)
print('auc',auc_roc)
print('pauc',pauc) | 2,836 | 35.371795 | 131 | py |
InvariantRuleAD | InvariantRuleAD-main/experiments/main_deepsvdd.py | '''
Created on Nov 9, 2022
@author: z003w5we
'''
import sys,getopt
sys.path.insert(0, "../")
from core.preprocessing.data_loader import DATASET,load_dataset
from core.preprocessing import DataUtil
from sklearn.metrics import roc_auc_score
from core.model.reconstruction_models.DeepSVDD import DeepSVDD
if __name__ == "__main__":
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "d:",["dataset="])
except:
print(u'python main_deepsvdd.py --dataset <dataset>')
sys.exit(2)
ds = None
gamma = None
theta = None
load_saved = False
for opt, arg in opts:
if opt in ['-d','--dataset']:
if arg.lower() == 'swat':
ds = DATASET.SWAT
elif arg.lower() == 'batadal':
ds = DATASET.BATADAL
elif arg.lower() == 'kddcup99':
ds = DATASET.KDDCup99
elif arg.lower() == 'gaspipeline':
ds = DATASET.GasPipeline
elif arg.lower() == 'annthyroid':
ds = DATASET.Annthyroid
elif arg.lower() == 'cardio':
ds = DATASET.Cardio
else:
print(u'python main_deepsvdd.py --dataset <dataset>')
sys.exit(2)
if ds is None:
print(u'please specify dataset!')
sys.exit(2)
print(ds)
train_df, test_df, test_labels, signals = load_dataset(ds)
du = DataUtil(signals, scaling_method='min_max')
train_df = du.normalize_and_encode(train_df)
test_df = du.normalize_and_encode(test_df)
model = DeepSVDD(signals)
model.train(train_df.values, z_dim=len(signals)//4+1, nu=0.01, hidden_layers=2, z_activation='tanh', batch_size=256,epochs=100, verbose=0)
scores = model.score_samples(test_df.values)
auc = roc_auc_score(test_labels, scores)
pauc = roc_auc_score(test_labels, scores, max_fpr=0.1)
print(ds)
print('AUC:',auc)
print('pAUC',pauc)
print()
| 1,983 | 27.342857 | 142 | py |
InvariantRuleAD | InvariantRuleAD-main/experiments/main_lof.py | import sys,getopt
sys.path.insert(0, "../")
from core.preprocessing.data_loader import load_dataset,DATASET
from sklearn.neighbors import LocalOutlierFactor
from core.preprocessing import DataUtil
from sklearn.metrics import roc_auc_score
if __name__ == "__main__":
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "d:",["dataset="])
except:
print(u'python main_lof.py --dataset <dataset>')
sys.exit(2)
ds = None
gamma = None
theta = None
load_saved = False
for opt, arg in opts:
if opt in ['-d','--dataset']:
if arg.lower() == 'swat':
ds = DATASET.SWAT
elif arg.lower() == 'batadal':
ds = DATASET.BATADAL
elif arg.lower() == 'kddcup99':
ds = DATASET.KDDCup99
elif arg.lower() == 'gaspipeline':
ds = DATASET.GasPipeline
elif arg.lower() == 'annthyroid':
ds = DATASET.Annthyroid
elif arg.lower() == 'cardio':
ds = DATASET.Cardio
else:
print(u'python main_lof.py --dataset <dataset>')
sys.exit(2)
if ds is None:
print(u'please specify dataset!')
sys.exit(2)
print(ds)
train_df,test_df,test_label,signals = load_dataset(ds)
du = DataUtil(signals,scaling_method='min_max')
train_df = du.normalize_and_encode(train_df)
test_df = du.normalize_and_encode(test_df)
model = LocalOutlierFactor(novelty=True)
model.fit(train_df.values)
true_labels = test_label
scores = model.decision_function(test_df.values)
scores = -1*scores
auc_roc = roc_auc_score(true_labels,scores)
pauc = roc_auc_score(true_labels,scores,max_fpr=0.1)
print('auc',auc_roc)
print('pauc',pauc)
print() | 1,876 | 27.876923 | 63 | py |
InvariantRuleAD | InvariantRuleAD-main/experiments/__init__.py | 0 | 0 | 0 | py | |
CLUE | CLUE-master/baselines/paddlenlp/classification/run_clue_classifier.py | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
import sys
import random
import time
import math
import json
import distutils.util
from functools import partial
import numpy as np
import paddle
from paddle.io import DataLoader
import paddle.nn as nn
from paddle.metric import Accuracy
from paddlenlp.datasets import load_dataset
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.transformers import LinearDecayWithWarmup
from paddlenlp.transformers import AutoModelForSequenceClassification, AutoTokenizer
from paddlenlp.utils.log import logger
METRIC_CLASSES = {
"afqmc": Accuracy,
"tnews": Accuracy,
"iflytek": Accuracy,
"ocnli": Accuracy,
"cmnli": Accuracy,
"cluewsc2020": Accuracy,
"csl": Accuracy,
}
def parse_args():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--task_name",
default=None,
type=str,
required=True,
help="The name of the task to train selected in the list: " +
", ".join(METRIC_CLASSES.keys()),
)
parser.add_argument("--model_name_or_path",
default=None,
type=str,
required=True,
help="Path to pre-trained model or shortcut name.")
parser.add_argument(
"--output_dir",
default="best_clue_model",
type=str,
help=
"The output directory where the model predictions and checkpoints will be written.",
)
parser.add_argument(
"--max_seq_length",
default=128,
type=int,
help=
"The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded.",
)
parser.add_argument("--learning_rate",
default=1e-4,
type=float,
help="The initial learning rate for Adam.")
parser.add_argument(
"--num_train_epochs",
default=3,
type=int,
help="Total number of training epochs to perform.",
)
parser.add_argument("--logging_steps",
type=int,
default=100,
help="Log every X updates steps.")
parser.add_argument("--save_steps",
type=int,
default=100,
help="Save checkpoint every X updates steps.")
parser.add_argument(
"--batch_size",
default=32,
type=int,
help="Batch size per GPU/CPU for training.",
)
parser.add_argument("--weight_decay",
default=0.0,
type=float,
help="Weight decay if we apply some.")
parser.add_argument(
"--warmup_steps",
default=0,
type=int,
help=
"Linear warmup over warmup_steps. If > 0: Override warmup_proportion")
parser.add_argument("--warmup_proportion",
default=0.1,
type=float,
help="Linear warmup proportion over total steps.")
parser.add_argument("--adam_epsilon",
default=1e-6,
type=float,
help="Epsilon for Adam optimizer.")
parser.add_argument(
'--gradient_accumulation_steps',
type=int,
default=1,
help=
"Number of updates steps to accumualte before performing a backward/update pass."
)
parser.add_argument("--do_train",
action='store_true',
help="Whether do train.")
parser.add_argument("--do_eval",
action='store_true',
help="Whether do train.")
parser.add_argument("--do_predict",
action='store_true',
help="Whether do predict.")
parser.add_argument(
"--max_steps",
default=-1,
type=int,
help=
"If > 0: set total number of training steps to perform. Override num_train_epochs.",
)
parser.add_argument(
"--save_best_model",
default=True,
type=distutils.util.strtobool,
help="Whether to save best model.",
)
parser.add_argument("--seed",
default=42,
type=int,
help="random seed for initialization")
parser.add_argument(
"--device",
default="gpu",
type=str,
help="The device to select to train the model, is must be cpu/gpu/xpu.")
parser.add_argument("--dropout", default=0.1, type=float, help="dropout.")
parser.add_argument("--max_grad_norm",
default=1.0,
type=float,
help="The max value of grad norm.")
args = parser.parse_args()
return args
def set_seed(args):
# Use the same data seed(for data shuffle) for all procs to guarantee data
# consistency after sharding.
random.seed(args.seed)
np.random.seed(args.seed)
# Maybe different op seeds(for dropout) for different procs is better. By:
# `paddle.seed(args.seed + paddle.distributed.get_rank())`
paddle.seed(args.seed)
@paddle.no_grad()
def evaluate(model, loss_fct, metric, data_loader):
model.eval()
metric.reset()
for batch in data_loader:
labels = batch.pop("labels")
logits = model(**batch)
loss = loss_fct(logits, labels)
correct = metric.compute(logits, labels)
metric.update(correct)
res = metric.accumulate()
logger.info("eval loss: %f, acc: %s, " % (loss.numpy(), res))
model.train()
return res
def convert_example(example,
tokenizer,
label_list,
is_test=False,
max_seq_length=512):
"""convert a glue example into necessary features"""
if not is_test:
# `label_list == None` is for regression task
label_dtype = "int64" if label_list else "float32"
# Get the label
label = np.array(example["label"], dtype="int64")
# Convert raw text to feature
if 'keyword' in example: # CSL
sentence1 = " ".join(example['keyword'])
example = {'sentence1': sentence1, 'sentence2': example['abst']}
elif 'target' in example: # wsc
text, query, pronoun, query_idx, pronoun_idx = example['text'], example[
'target']['span1_text'], example['target']['span2_text'], example[
'target']['span1_index'], example['target']['span2_index']
text_list = list(text)
assert text[pronoun_idx:(
pronoun_idx +
len(pronoun))] == pronoun, "pronoun: {}".format(pronoun)
assert text[query_idx:(query_idx +
len(query))] == query, "query: {}".format(query)
if pronoun_idx > query_idx:
text_list.insert(query_idx, "_")
text_list.insert(query_idx + len(query) + 1, "_")
text_list.insert(pronoun_idx + 2, "[")
text_list.insert(pronoun_idx + len(pronoun) + 2 + 1, "]")
else:
text_list.insert(pronoun_idx, "[")
text_list.insert(pronoun_idx + len(pronoun) + 1, "]")
text_list.insert(query_idx + 2, "_")
text_list.insert(query_idx + len(query) + 2 + 1, "_")
text = "".join(text_list)
example['sentence'] = text
if 'sentence' in example:
example = tokenizer(example['sentence'], max_seq_len=max_seq_length)
elif 'sentence1' in example:
example = tokenizer(example['sentence1'],
text_pair=example['sentence2'],
max_seq_len=max_seq_length)
if not is_test:
example["labels"] = label
return example
def do_eval(args):
paddle.set_device(args.device)
if paddle.distributed.get_world_size() > 1:
paddle.distributed.init_parallel_env()
set_seed(args)
args.task_name = args.task_name.lower()
metric_class = METRIC_CLASSES[args.task_name]
dev_ds = load_dataset('clue', args.task_name, splits='dev')
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
trans_func = partial(convert_example,
label_list=dev_ds.label_list,
tokenizer=tokenizer,
max_seq_length=args.max_seq_length)
dev_ds = dev_ds.map(trans_func, lazy=True)
dev_batch_sampler = paddle.io.BatchSampler(dev_ds,
batch_size=args.batch_size,
shuffle=False)
batchify_fn = DataCollatorWithPadding(tokenizer)
dev_data_loader = DataLoader(dataset=dev_ds,
batch_sampler=dev_batch_sampler,
collate_fn=batchify_fn,
num_workers=0,
return_list=True)
num_classes = 1 if dev_ds.label_list == None else len(dev_ds.label_list)
model = AutoModelForSequenceClassification.from_pretrained(
args.model_name_or_path, num_classes=num_classes)
if paddle.distributed.get_world_size() > 1:
model = paddle.DataParallel(model)
metric = metric_class()
best_acc = 0.0
global_step = 0
tic_train = time.time()
model.eval()
metric.reset()
for batch in dev_data_loader:
labels = batch.pop("labels")
logits = model(**batch)
correct = metric.compute(logits, labels)
metric.update(correct)
res = metric.accumulate()
logger.info("acc: %s\n, " % (res))
def do_train(args):
assert args.batch_size % args.gradient_accumulation_steps == 0, \
"Please make sure argmument `batch_size` must be divisible by `gradient_accumulation_steps`."
paddle.set_device(args.device)
if paddle.distributed.get_world_size() > 1:
paddle.distributed.init_parallel_env()
set_seed(args)
args.task_name = args.task_name.lower()
metric_class = METRIC_CLASSES[args.task_name]
args.batch_size = int(args.batch_size / args.gradient_accumulation_steps)
train_ds, dev_ds = load_dataset('clue',
args.task_name,
splits=('train', 'dev'))
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
trans_func = partial(convert_example,
label_list=train_ds.label_list,
tokenizer=tokenizer,
max_seq_length=args.max_seq_length)
train_ds = train_ds.map(trans_func, lazy=True)
train_batch_sampler = paddle.io.DistributedBatchSampler(
train_ds, batch_size=args.batch_size, shuffle=True)
dev_ds = dev_ds.map(trans_func, lazy=True)
dev_batch_sampler = paddle.io.BatchSampler(dev_ds,
batch_size=args.batch_size,
shuffle=False)
batchify_fn = DataCollatorWithPadding(tokenizer)
train_data_loader = DataLoader(dataset=train_ds,
batch_sampler=train_batch_sampler,
collate_fn=batchify_fn,
num_workers=0,
return_list=True)
dev_data_loader = DataLoader(dataset=dev_ds,
batch_sampler=dev_batch_sampler,
collate_fn=batchify_fn,
num_workers=0,
return_list=True)
num_classes = 1 if train_ds.label_list == None else len(train_ds.label_list)
model = AutoModelForSequenceClassification.from_pretrained(
args.model_name_or_path, num_classes=num_classes)
if args.dropout != 0.1:
update_model_dropout(model, args.dropout)
if paddle.distributed.get_world_size() > 1:
model = paddle.DataParallel(model)
if args.max_steps > 0:
num_training_steps = args.max_steps / args.gradient_accumulation_steps
num_train_epochs = math.ceil(num_training_steps /
len(train_data_loader))
else:
num_training_steps = len(
train_data_loader
) * args.num_train_epochs / args.gradient_accumulation_steps
num_train_epochs = args.num_train_epochs
warmup = args.warmup_steps if args.warmup_steps > 0 else args.warmup_proportion
lr_scheduler = LinearDecayWithWarmup(args.learning_rate, num_training_steps,
warmup)
# Generate parameter names needed to perform weight decay.
# All bias and LayerNorm parameters are excluded.
decay_params = [
p.name for n, p in model.named_parameters()
if not any(nd in n for nd in ["bias", "norm"])
]
optimizer = paddle.optimizer.AdamW(
learning_rate=lr_scheduler,
beta1=0.9,
beta2=0.999,
epsilon=args.adam_epsilon,
parameters=model.parameters(),
weight_decay=args.weight_decay,
apply_decay_param_fun=lambda x: x in decay_params,
grad_clip=nn.ClipGradByGlobalNorm(args.max_grad_norm))
loss_fct = paddle.nn.loss.CrossEntropyLoss(
) if train_ds.label_list else paddle.nn.loss.MSELoss()
metric = metric_class()
best_acc = 0.0
global_step = 0
tic_train = time.time()
for epoch in range(num_train_epochs):
for step, batch in enumerate(train_data_loader):
labels = batch.pop("labels")
logits = model(**batch)
loss = loss_fct(logits, labels)
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
loss.backward()
if (step + 1) % args.gradient_accumulation_steps == 0:
global_step += 1
optimizer.step()
lr_scheduler.step()
optimizer.clear_grad()
if global_step % args.logging_steps == 0:
logger.info(
"global step %d/%d, epoch: %d, batch: %d, rank_id: %s, loss: %f, lr: %.10f, speed: %.4f step/s"
% (global_step, num_training_steps, epoch, step,
paddle.distributed.get_rank(), loss,
optimizer.get_lr(), args.logging_steps /
(time.time() - tic_train)))
tic_train = time.time()
if global_step % args.save_steps == 0 or global_step == num_training_steps:
tic_eval = time.time()
acc = evaluate(model, loss_fct, metric, dev_data_loader)
logger.info("eval done total : %s s" %
(time.time() - tic_eval))
if acc > best_acc:
best_acc = acc
if args.save_best_model:
output_dir = args.output_dir
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Need better way to get inner model of DataParallel
model_to_save = model._layers if isinstance(
model, paddle.DataParallel) else model
model_to_save.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)
if global_step >= num_training_steps:
logger.info("best_result: %.2f" % (best_acc * 100))
return
logger.info("best_result: %.2f" % (best_acc * 100))
def do_predict(args):
paddle.set_device(args.device)
args.task_name = args.task_name.lower()
train_ds, test_ds = load_dataset('clue',
args.task_name,
splits=('train', 'test'))
if args.task_name == "cluewsc2020" or args.task_name == "tnews":
test_ds_10 = load_dataset('clue', args.task_name, splits="test1.0")
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
trans_func = partial(convert_example,
tokenizer=tokenizer,
label_list=train_ds.label_list,
max_seq_length=args.max_seq_length,
is_test=True)
batchify_fn = DataCollatorWithPadding(tokenizer)
test_ds = test_ds.map(trans_func, lazy=True)
test_batch_sampler = paddle.io.BatchSampler(test_ds,
batch_size=args.batch_size,
shuffle=False)
test_data_loader = DataLoader(dataset=test_ds,
batch_sampler=test_batch_sampler,
collate_fn=batchify_fn,
num_workers=0,
return_list=True)
if args.task_name == "cluewsc2020" or args.task_name == "tnews":
test_ds_10 = test_ds_10.map(trans_func, lazy=True)
test_batch_sampler_10 = paddle.io.BatchSampler(
test_ds_10, batch_size=args.batch_size, shuffle=False)
test_data_loader_10 = DataLoader(dataset=test_ds_10,
batch_sampler=test_batch_sampler_10,
collate_fn=batchify_fn,
num_workers=0,
return_list=True)
num_classes = 1 if train_ds.label_list == None else len(train_ds.label_list)
model = AutoModelForSequenceClassification.from_pretrained(
args.model_name_or_path, num_classes=num_classes)
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
prediction_filename = args.task_name
if args.task_name == 'ocnli':
prediction_filename = 'ocnli_50k'
elif args.task_name == "cluewsc2020":
prediction_filename = "cluewsc" + "11"
elif args.task_name == "tnews":
prediction_filename = args.task_name + "11"
# For version 1.1
f = open(
os.path.join(args.output_dir, prediction_filename + "_predict.json"),
'w')
preds = []
for step, batch in enumerate(test_data_loader):
with paddle.no_grad():
logits = model(**batch)
pred = paddle.argmax(logits, axis=1).numpy().tolist()
preds += pred
for idx, pred in enumerate(preds):
j = json.dumps({"id": idx, "label": train_ds.label_list[pred]})
f.write(j + "\n")
# For version 1.0
if args.task_name == "cluewsc2020" or args.task_name == "tnews":
prediction_filename = args.task_name + "10"
if args.task_name == "cluewsc2020":
prediction_filename = "cluewsc10"
f = open(
os.path.join(args.output_dir,
prediction_filename + "_predict.json"), 'w')
preds = []
for step, batch in enumerate(test_data_loader_10):
with paddle.no_grad():
logits = model(**batch)
pred = paddle.argmax(logits, axis=1).numpy().tolist()
preds += pred
for idx, pred in enumerate(preds):
j = json.dumps({"id": idx, "label": train_ds.label_list[pred]})
f.write(j + "\n")
def print_arguments(args):
"""print arguments"""
print('----------- Configuration Arguments -----------')
for arg, value in sorted(vars(args).items()):
print('%s: %s' % (arg, value))
print('------------------------------------------------')
def update_model_dropout(model, p=0.0):
model.base_model.embeddings.dropout.p = p
for i in range(len(model.base_model.encoder.layers)):
model.base_model.encoder.layers[i].dropout.p = p
model.base_model.encoder.layers[i].dropout1.p = p
model.base_model.encoder.layers[i].dropout2.p = p
if __name__ == "__main__":
args = parse_args()
print_arguments(args)
if args.do_train:
do_train(args)
if args.do_eval:
do_eval(args)
if args.do_predict:
do_predict(args)
| 20,966 | 37.260949 | 119 | py |
CLUE | CLUE-master/baselines/paddlenlp/classification/run_clue_classifier_trainer.py | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
from functools import partial
from typing import Optional
from dataclasses import dataclass, field
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle.metric import Accuracy
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.datasets import load_dataset
from paddlenlp.trainer import (
PdArgumentParser,
TrainingArguments,
Trainer,
)
from paddlenlp.trainer import get_last_checkpoint
from paddlenlp.transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
)
from paddlenlp.utils.log import logger
@dataclass
class DataArguments:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
Using `PdArgumentParser` we can turn this class into argparse arguments to be able to
specify them on the command line.
"""
dataset: str = field(
default=None,
metadata={
"help": "The name of the dataset to use (via the datasets library)."
})
max_seq_length: int = field(
default=128,
metadata={
"help":
"The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
},
)
do_lower_case: bool = field(
default=False,
metadata={
"help":
"Whether to lower case the input text. Should be True for uncased models and False for cased models."
},
)
@dataclass
class ModelArguments:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
metadata={
"help":
"Path to pretrained model or model identifier from https://paddlenlp.readthedocs.io/zh/latest/model_zoo/transformers.html"
})
config_name: Optional[str] = field(
default=None,
metadata={
"help":
"Pretrained config name or path if not the same as model_name"
})
tokenizer_name: Optional[str] = field(
default=None,
metadata={
"help":
"Pretrained tokenizer name or path if not the same as model_name"
})
cache_dir: Optional[str] = field(
default=None,
metadata={"help": "Path to directory to store the dataset cache."},
)
export_model_dir: Optional[str] = field(
default=None,
metadata={
"help": "Path to directory to store the exported inference model."
},
)
# Data pre-process function for clue benchmark datatset
def convert_clue(example,
label_list,
tokenizer=None,
max_seq_length=512,
**kwargs):
"""convert a glue example into necessary features"""
is_test = False
if 'label' not in example.keys():
is_test = True
if not is_test:
# `label_list == None` is for regression task
label_dtype = "int64" if label_list else "float32"
# print("label_list", label_list)
# Get the label
# example['label'] = np.array(example["label"], dtype="int64")
example['label'] = int(
example["label"]) if label_dtype != "float32" else float(
example["label"])
label = example['label']
# Convert raw text to feature
if 'keyword' in example: # CSL
sentence1 = " ".join(example['keyword'])
example = {
'sentence1': sentence1,
'sentence2': example['abst'],
'label': example['label']
}
elif 'target' in example: # wsc
text, query, pronoun, query_idx, pronoun_idx = example['text'], example[
'target']['span1_text'], example['target']['span2_text'], example[
'target']['span1_index'], example['target']['span2_index']
text_list = list(text)
assert text[pronoun_idx:(
pronoun_idx +
len(pronoun))] == pronoun, "pronoun: {}".format(pronoun)
assert text[query_idx:(query_idx +
len(query))] == query, "query: {}".format(query)
if pronoun_idx > query_idx:
text_list.insert(query_idx, "_")
text_list.insert(query_idx + len(query) + 1, "_")
text_list.insert(pronoun_idx + 2, "[")
text_list.insert(pronoun_idx + len(pronoun) + 2 + 1, "]")
else:
text_list.insert(pronoun_idx, "[")
text_list.insert(pronoun_idx + len(pronoun) + 1, "]")
text_list.insert(query_idx + 2, "_")
text_list.insert(query_idx + len(query) + 2 + 1, "_")
text = "".join(text_list)
example['sentence'] = text
if tokenizer is None:
return example
if 'sentence' in example:
example = tokenizer(example['sentence'], max_seq_len=max_seq_length)
elif 'sentence1' in example:
example = tokenizer(example['sentence1'],
text_pair=example['sentence2'],
max_seq_len=max_seq_length)
if not is_test:
return {
"input_ids": example['input_ids'],
"token_type_ids": example['token_type_ids'],
"labels": label
}
else:
return {
"input_ids": example['input_ids'],
"token_type_ids": example['token_type_ids']
}
def clue_trans_fn(example, tokenizer, args):
return convert_clue(example,
tokenizer=tokenizer,
label_list=args.label_list,
max_seq_length=args.max_seq_length)
def main():
parser = PdArgumentParser(
(ModelArguments, DataArguments, TrainingArguments))
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
# Log model and data config
training_args.print_config(model_args, "Model")
training_args.print_config(data_args, "Data")
paddle.set_device(training_args.device)
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, world_size: {training_args.world_size}, "
+
f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
)
# Detecting last checkpoint.
last_checkpoint = None
if os.path.isdir(
training_args.output_dir
) and training_args.do_train and not training_args.overwrite_output_dir:
last_checkpoint = get_last_checkpoint(training_args.output_dir)
if last_checkpoint is None and len(os.listdir(
training_args.output_dir)) > 0:
raise ValueError(
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
"Use --overwrite_output_dir to overcome.")
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
logger.info(
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
)
data_args.dataset = data_args.dataset.strip()
dataset_config = data_args.dataset.split(" ")
print(dataset_config)
raw_datasets = load_dataset(
dataset_config[0],
name=None if len(dataset_config) <= 1 else dataset_config[1],
splits=('train', 'dev'))
data_args.label_list = getattr(raw_datasets['train'], "label_list", None)
num_classes = 1 if raw_datasets["train"].label_list == None else len(
raw_datasets['train'].label_list)
# Define tokenizer, model, loss function.
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
model = AutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path, num_classes=num_classes)
criterion = nn.loss.CrossEntropyLoss(
) if data_args.label_list else nn.loss.MSELoss()
# Define dataset pre-process function
trans_fn = partial(clue_trans_fn, tokenizer=tokenizer, args=data_args)
# Define data collector
data_collator = DataCollatorWithPadding(tokenizer)
# Dataset pre-process
if training_args.do_train:
train_dataset = raw_datasets["train"].map(trans_fn)
if training_args.do_eval:
eval_dataset = raw_datasets["dev"].map(trans_fn)
if training_args.do_predict:
test_dataset = raw_datasets["test"].map(trans_fn)
# Define the metrics of tasks.
def compute_metrics(p):
preds = p.predictions[0] if isinstance(p.predictions,
tuple) else p.predictions
preds = paddle.to_tensor(preds)
label = paddle.to_tensor(p.label_ids)
probs = F.softmax(preds, axis=1)
metric = Accuracy()
metric.reset()
result = metric.compute(preds, label)
metric.update(result)
accu = metric.accumulate()
metric.reset()
return {"accuracy": accu}
trainer = Trainer(
model=model,
criterion=criterion,
args=training_args,
data_collator=data_collator,
train_dataset=train_dataset if training_args.do_train else None,
eval_dataset=eval_dataset if training_args.do_eval else None,
tokenizer=tokenizer,
compute_metrics=compute_metrics,
)
checkpoint = None
if training_args.resume_from_checkpoint is not None:
checkpoint = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
checkpoint = last_checkpoint
# Training
if training_args.do_train:
train_result = trainer.train(resume_from_checkpoint=checkpoint)
metrics = train_result.metrics
trainer.save_model()
trainer.log_metrics("train", metrics)
trainer.save_metrics("train", metrics)
trainer.save_state()
# Evaluate and tests model
if training_args.do_eval:
eval_metrics = trainer.evaluate()
trainer.log_metrics("eval", eval_metrics)
if training_args.do_predict:
test_ret = trainer.predict(test_dataset)
trainer.log_metrics("test", test_ret.metrics)
if test_ret.label_ids is None:
paddle.save(
test_ret.predictions,
os.path.join(training_args.output_dir, "test_results.pdtensor"),
)
# export inference model
if training_args.do_export:
# You can also load from certain checkpoint
# trainer.load_state_dict_from_checkpoint("/path/to/checkpoint/")
input_spec = [
paddle.static.InputSpec(shape=[None, None],
dtype="int64"), # input_ids
paddle.static.InputSpec(shape=[None, None],
dtype="int64") # segment_ids
]
if model_args.export_model_dir is None:
model_args.export_model_dir = os.path.join(training_args.output_dir,
"export")
paddlenlp.transformers.export_model(model=trainer.model,
input_spec=input_spec,
path=model_args.export_model_dir)
if __name__ == "__main__":
main()
| 12,065 | 35.125749 | 134 | py |
CLUE | CLUE-master/baselines/paddlenlp/mrc/run_chid.py | # coding: utf-8
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import time
import argparse
import json
import distutils.util
import random
from functools import partial
import contextlib
import numpy as np
import paddle
import paddle.nn as nn
from datasets import load_dataset
from paddlenlp.data import Pad, Stack, Tuple, Dict
from paddlenlp.transformers import AutoModelForMultipleChoice, AutoTokenizer
from paddlenlp.transformers import LinearDecayWithWarmup
from paddlenlp.utils.log import logger
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--device",
default="gpu",
type=str,
help="The device to select to train the model, is must be cpu/gpu/xpu.")
parser.add_argument("--model_name_or_path",
default=None,
type=str,
required=True,
help="Path to pre-trained model or shortcut name.")
parser.add_argument("--output_dir",
default="best_chid_model",
type=str,
help="The path of the checkpoints .")
parser.add_argument("--save_best_model",
default=True,
type=distutils.util.strtobool,
help="Whether to save best model.")
parser.add_argument("--overwrite_cache",
default=False,
type=distutils.util.strtobool,
help="Whether to overwrite cache for dataset.")
parser.add_argument("--num_train_epochs",
default=3,
type=int,
help="Total number of training epochs to perform.")
parser.add_argument(
"--num_proc",
default=None,
type=int,
help=
"Max number of processes when generating cache. Already cached shards are loaded sequentially."
)
parser.add_argument("--weight_decay",
default=0.0,
type=float,
help="Weight decay if we apply some.")
parser.add_argument(
"--max_steps",
default=-1,
type=int,
help=
"If > 0: set total number of training steps to perform. Override num_train_epochs."
)
parser.add_argument("--warmup_proportion",
default=0.1,
type=float,
help="Linear warmup proportion over total steps.")
parser.add_argument(
"--warmup_steps",
default=0,
type=int,
help=
"Linear warmup over warmup_steps. If > 0: Override warmup_proportion")
parser.add_argument("--adam_epsilon",
default=1e-6,
type=float,
help="Epsilon for Adam optimizer.")
parser.add_argument("--learning_rate",
default=2e-5,
type=float,
help="The initial learning rate for Adam.")
parser.add_argument("--seed",
default=42,
type=int,
help="random seed for initialization")
parser.add_argument("--max_grad_norm",
default=1.0,
type=float,
help="The max value of grad norm.")
parser.add_argument("--batch_size",
default=4,
type=int,
help="Batch size per GPU/CPU for training.")
parser.add_argument("--eval_batch_size",
default=24,
type=int,
help="Batch size per GPU/CPU for training.")
parser.add_argument(
'--gradient_accumulation_steps',
type=int,
default=1,
help=
"Number of updates steps to accumualte before performing a backward/update pass."
)
parser.add_argument("--do_train",
action='store_true',
help="Whether to train.")
parser.add_argument("--do_predict",
action='store_true',
help="Whether to predict.")
parser.add_argument(
"--max_seq_length",
default=64,
type=int,
help=
"The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded.")
parser.add_argument("--logging_steps",
type=int,
default=100,
help="Log every X updates steps.")
args = parser.parse_args()
return args
def set_seed(args):
# Use the same data seed(for data shuffle) for all procs to guarantee data
# consistency after sharding.
random.seed(args.seed)
np.random.seed(args.seed)
# Maybe different op seeds(for dropout) for different procs is better. By:
# `paddle.seed(args.seed + paddle.distributed.get_rank())`
paddle.seed(args.seed)
def calc_global_pred_results(logits):
logits = np.array(logits)
# [num_choices, tag_size]
logits = np.transpose(logits)
tmp = []
for i, row in enumerate(logits):
for j, col in enumerate(row):
tmp.append((i, j, col))
else:
choice = set(range(i + 1))
blanks = set(range(j + 1))
tmp = sorted(tmp, key=lambda x: x[2], reverse=True)
results = []
for i, j, v in tmp:
if (j in blanks) and (i in choice):
results.append((i, j))
blanks.remove(j)
choice.remove(i)
results = sorted(results, key=lambda x: x[1], reverse=False)
results = [i for i, j in results]
return results
@paddle.no_grad()
def evaluate(model, data_loader, do_predict=False):
model.eval()
right_num, total_num = 0, 0
all_results = []
for step, batch in enumerate(data_loader):
if do_predict:
input_ids, segment_ids, example_ids = batch
else:
input_ids, segment_ids, labels, example_ids = batch
logits = model(input_ids=input_ids, token_type_ids=segment_ids)
batch_num = example_ids.shape[0]
l = 0
r = batch_num - 1
batch_results = []
for i in range(batch_num - 1):
if example_ids[i] != example_ids[i + 1]:
r = i
batch_results.extend(
calc_global_pred_results(logits[l:r + 1, :]))
l = i + 1
if l <= batch_num - 1:
batch_results.extend(
calc_global_pred_results(logits[l:batch_num, :]))
if do_predict:
all_results.extend(batch_results)
else:
right_num += np.sum(np.array(batch_results) == labels.numpy())
total_num += labels.shape[0]
model.train()
if not do_predict:
acc = right_num / total_num
return acc
return all_results
@contextlib.contextmanager
def main_process_first(desc="work"):
if paddle.distributed.get_world_size() > 1:
rank = paddle.distributed.get_rank()
is_main_process = rank == 0
main_process_desc = "main local process"
try:
if not is_main_process:
# tell all replicas to wait
logger.debug(
f"{rank}: waiting for the {main_process_desc} to perform {desc}"
)
paddle.distributed.barrier()
yield
finally:
if is_main_process:
# the wait is over
logger.debug(
f"{rank}: {main_process_desc} completed {desc}, releasing all replicas"
)
paddle.distributed.barrier()
else:
yield
def run(args):
if args.do_train:
assert args.batch_size % args.gradient_accumulation_steps == 0, \
"Please make sure argmument `batch_size` must be divisible by `gradient_accumulation_steps`."
paddle.set_device(args.device)
set_seed(args)
max_seq_length = args.max_seq_length
max_num_choices = 10
def preprocess_function(examples, do_predict=False):
SPIECE_UNDERLINE = '▁'
def _is_chinese_char(cp):
if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
(cp >= 0x3400 and cp <= 0x4DBF) or #
(cp >= 0x20000 and cp <= 0x2A6DF) or #
(cp >= 0x2A700 and cp <= 0x2B73F) or #
(cp >= 0x2B740 and cp <= 0x2B81F) or #
(cp >= 0x2B820 and cp <= 0x2CEAF) or
(cp >= 0xF900 and cp <= 0xFAFF) or #
(cp >= 0x2F800 and cp <= 0x2FA1F)): #
return True
return False
def is_fuhao(c):
if c == '。' or c == ',' or c == '!' or c == '?' or c == ';' or c == '、' or c == ':' or c == '(' or c == ')' \
or c == '-' or c == '~' or c == '「' or c == '《' or c == '》' or c == ',' or c == '」' or c == '"' or c == '“' or c == '”' \
or c == '$' or c == '『' or c == '』' or c == '—' or c == ';' or c == '。' or c == '(' or c == ')' or c == '-' or c == '~' or c == '。' \
or c == '‘' or c == '’':
return True
return False
def _tokenize_chinese_chars(text):
"""Adds whitespace around any CJK character."""
output = []
is_blank = False
for index, char in enumerate(text):
cp = ord(char)
if is_blank:
output.append(char)
if context[index - 12:index + 1].startswith("#idiom"):
is_blank = False
output.append(SPIECE_UNDERLINE)
else:
if text[index:index + 6] == "#idiom":
is_blank = True
if len(output) > 0 and output[-1] != SPIECE_UNDERLINE:
output.append(SPIECE_UNDERLINE)
output.append(char)
elif _is_chinese_char(cp) or is_fuhao(char):
if len(output) > 0 and output[-1] != SPIECE_UNDERLINE:
output.append(SPIECE_UNDERLINE)
output.append(char)
output.append(SPIECE_UNDERLINE)
else:
output.append(char)
return "".join(output)
def is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(
c) == 0x202F or c == SPIECE_UNDERLINE:
return True
return False
def add_tokens_for_around(tokens, pos, num_tokens):
num_l = num_tokens // 2
num_r = num_tokens - num_l
if pos >= num_l and (len(tokens) - 1 - pos) >= num_r:
tokens_l = tokens[pos - num_l:pos]
tokens_r = tokens[pos + 1:pos + 1 + num_r]
elif pos <= num_l:
tokens_l = tokens[:pos]
right_len = num_tokens - len(tokens_l)
tokens_r = tokens[pos + 1:pos + 1 + right_len]
elif (len(tokens) - 1 - pos) <= num_r:
tokens_r = tokens[pos + 1:]
left_len = num_tokens - len(tokens_r)
tokens_l = tokens[pos - left_len:pos]
else:
raise ValueError('impossible')
return tokens_l, tokens_r
max_tokens_for_doc = max_seq_length - 3
num_tokens = max_tokens_for_doc - 5
num_examples = len(examples.data["candidates"])
if do_predict:
result = {"input_ids": [], "token_type_ids": [], "example_ids": []}
else:
result = {
"input_ids": [],
"token_type_ids": [],
"labels": [],
"example_ids": []
}
for idx in range(num_examples):
candidate = 0
options = examples.data['candidates'][idx]
# Each content may have several sentences.
for context in examples.data['content'][idx]:
context = context.replace("“", "\"").replace("”", "\"").replace("——", "--"). \
replace("—", "-").replace("―", "-").replace("…", "...").replace("‘", "\'").replace("’", "\'")
context = _tokenize_chinese_chars(context)
paragraph_text = context.strip()
doc_tokens = []
prev_is_whitespace = True
for c in paragraph_text:
if is_whitespace(c):
prev_is_whitespace = True
else:
if prev_is_whitespace:
doc_tokens.append(c)
else:
doc_tokens[-1] += c
prev_is_whitespace = False
all_doc_tokens = []
for (i, token) in enumerate(doc_tokens):
if '#idiom' in token:
sub_tokens = [str(token)]
else:
sub_tokens = tokenizer.tokenize(token)
for sub_token in sub_tokens:
all_doc_tokens.append(sub_token)
tags = [blank for blank in doc_tokens if '#idiom' in blank]
# Each sentence may have several tags
for tag_index, tag in enumerate(tags):
pos = all_doc_tokens.index(tag)
tmp_l, tmp_r = add_tokens_for_around(
all_doc_tokens, pos, num_tokens)
num_l = len(tmp_l)
num_r = len(tmp_r)
tokens_l = []
for token in tmp_l:
if '#idiom' in token and token != tag:
# Mask tag which is not considered in this new sample.
# Each idiom has four words, so 4 mask tokens are used.
tokens_l.extend(['[MASK]'] * 4)
else:
tokens_l.append(token)
tokens_l = tokens_l[-num_l:]
del tmp_l
tokens_r = []
for token in tmp_r:
if '#idiom' in token and token != tag:
tokens_r.extend(['[MASK]'] * 4)
else:
tokens_r.append(token)
tokens_r = tokens_r[:num_r]
del tmp_r
tokens_list = []
# Each tag has ten choices, and the shape of each new
# example is [num_choices, seq_len]
for i, elem in enumerate(options):
option = tokenizer.tokenize(elem)
tokens = option + ['[SEP]'] + tokens_l + ['[unused1]'
] + tokens_r
tokens_list.append(tokens)
new_data = tokenizer(tokens_list, is_split_into_words=True)
# Final shape of input_ids: [batch_size, num_choices, seq_len]
result["input_ids"].append(new_data["input_ids"])
result["token_type_ids"].append(new_data["token_type_ids"])
result["example_ids"].append(idx)
if not do_predict:
label = examples.data["answers"][idx]["candidate_id"][
candidate]
result["labels"].append(label)
candidate += 1
if (idx + 1) % 10000 == 0:
logger.info("%d samples have been processed." % (idx + 1))
return result
if paddle.distributed.get_world_size() > 1:
paddle.distributed.init_parallel_env()
model = AutoModelForMultipleChoice.from_pretrained(
args.model_name_or_path, num_choices=max_num_choices)
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
if paddle.distributed.get_world_size() > 1:
model = paddle.DataParallel(model)
train_ds, dev_ds, test_ds = load_dataset(
"clue", "chid", split=["train", "validation", "test"])
if args.do_train:
args.batch_size = int(args.batch_size /
args.gradient_accumulation_steps)
column_names = train_ds.column_names
with main_process_first(desc="train dataset map pre-processing"):
train_ds = train_ds.map(
partial(preprocess_function),
batched=True,
batch_size=len(train_ds),
num_proc=args.num_proc,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc="Running tokenizer on train dataset")
batchify_fn = lambda samples, fn=Dict(
{
'input_ids': Pad(axis=1, pad_val=tokenizer.pad_token_id
), # input
'token_type_ids': Pad(
axis=1, pad_val=tokenizer.pad_token_type_id), # segment
'labels': Stack(dtype="int64"), # label
'example_ids': Stack(dtype="int64"), # example id
}): fn(samples)
train_batch_sampler = paddle.io.DistributedBatchSampler(
train_ds, batch_size=args.batch_size, shuffle=True)
train_data_loader = paddle.io.DataLoader(
dataset=train_ds,
batch_sampler=train_batch_sampler,
collate_fn=batchify_fn,
num_workers=0,
return_list=True)
with main_process_first(desc="evaluate dataset map pre-processing"):
dev_ds = dev_ds.map(partial(preprocess_function),
batched=True,
batch_size=len(dev_ds),
remove_columns=column_names,
num_proc=args.num_proc,
load_from_cache_file=args.overwrite_cache,
desc="Running tokenizer on validation dataset")
dev_batch_sampler = paddle.io.BatchSampler(
dev_ds, batch_size=args.eval_batch_size, shuffle=False)
dev_data_loader = paddle.io.DataLoader(dataset=dev_ds,
batch_sampler=dev_batch_sampler,
collate_fn=batchify_fn,
return_list=True)
num_training_steps = int(
args.max_steps /
args.gradient_accumulation_steps) if args.max_steps >= 0 else int(
len(train_data_loader) * args.num_train_epochs /
args.gradient_accumulation_steps)
warmup = args.warmup_steps if args.warmup_steps > 0 else args.warmup_proportion
lr_scheduler = LinearDecayWithWarmup(args.learning_rate,
num_training_steps, warmup)
# Generate parameter names needed to perform weight decay.
# All bias and LayerNorm parameters are excluded.
decay_params = [
p.name for n, p in model.named_parameters()
if not any(nd in n for nd in ["bias", "norm"])
]
grad_clip = paddle.nn.ClipGradByGlobalNorm(args.max_grad_norm)
optimizer = paddle.optimizer.AdamW(
learning_rate=lr_scheduler,
parameters=model.parameters(),
weight_decay=args.weight_decay,
apply_decay_param_fun=lambda x: x in decay_params,
grad_clip=grad_clip)
loss_fct = nn.CrossEntropyLoss()
model.train()
global_step = 0
best_acc = 0.0
tic_train = time.time()
for epoch in range(args.num_train_epochs):
for step, batch in enumerate(train_data_loader):
input_ids, segment_ids, labels, example_ids = batch
logits = model(input_ids=input_ids, token_type_ids=segment_ids)
loss = loss_fct(logits, labels)
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
loss.backward()
if (step + 1) % args.gradient_accumulation_steps == 0:
global_step += 1
optimizer.step()
lr_scheduler.step()
optimizer.clear_grad()
if global_step % args.logging_steps == 0:
logger.info(
"global step %d/%d, epoch: %d, batch: %d, loss: %.5f, speed: %.2f step/s"
% (global_step, num_training_steps, epoch, step + 1,
loss, args.logging_steps /
(time.time() - tic_train)))
tic_train = time.time()
if global_step >= num_training_steps:
break
if global_step > num_training_steps:
break
tic_eval = time.time()
acc = evaluate(model, dev_data_loader)
logger.info("eval acc: %.5f, eval done total : %s s" %
(acc, time.time() - tic_eval))
if paddle.distributed.get_rank() == 0 and acc > best_acc:
best_acc = acc
if args.save_best_model:
model_to_save = model._layers if isinstance(
model, paddle.DataParallel) else model
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
model_to_save.save_pretrained(args.output_dir)
tokenizer.save_pretrained(args.output_dir)
if global_step >= num_training_steps:
break
logger.info("best_result: %.2f" % (best_acc * 100))
if args.do_predict:
column_names = test_ds.column_names
test_ds = test_ds.map(partial(preprocess_function, do_predict=True),
batched=True,
batch_size=len(test_ds),
remove_columns=column_names,
num_proc=args.num_proc)
test_batch_sampler = paddle.io.BatchSampler(
test_ds, batch_size=args.eval_batch_size, shuffle=False)
batchify_fn = lambda samples, fn=Dict({
'input_ids':
Pad(axis=1, pad_val=tokenizer.pad_token_id), # input
'token_type_ids':
Pad(axis=1, pad_val=tokenizer.pad_token_type_id), # segment
'example_ids':
Stack(dtype="int64"), # example id
}): fn(samples)
test_data_loader = paddle.io.DataLoader(
dataset=test_ds,
batch_sampler=test_batch_sampler,
collate_fn=batchify_fn,
return_list=True)
result = {}
idx = 623377
preds = evaluate(model, test_data_loader, do_predict=True)
for pred in preds:
result["#idiom" + str(idx) + "#"] = pred
idx += 1
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
with open(os.path.join(args.output_dir, 'chid11_predict.json'),
"w") as writer:
json.dump(result, writer, indent=2)
def print_arguments(args):
"""print arguments"""
print('----------- Configuration Arguments -----------')
for arg, value in sorted(vars(args).items()):
print('%s: %s' % (arg, value))
print('------------------------------------------------')
if __name__ == "__main__":
args = parse_args()
print_arguments(args)
run(args)
| 24,584 | 39.975 | 153 | py |
CLUE | CLUE-master/baselines/paddlenlp/mrc/run_c3.py | # coding: utf-8
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import time
import random
import argparse
import numpy as np
import json
import distutils.util
from functools import partial
import contextlib
import paddle
import paddle.nn as nn
from datasets import load_dataset
from paddlenlp.data import Stack, Dict, Pad, Tuple
from paddlenlp.transformers import LinearDecayWithWarmup
from paddlenlp.transformers import AutoModelForMultipleChoice, AutoTokenizer
from paddlenlp.utils.log import logger
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--device",
default="gpu",
type=str,
help="The device to select to train the model, is must be cpu/gpu/xpu.")
parser.add_argument("--model_name_or_path",
default=None,
type=str,
required=True,
help="Path to pre-trained model or shortcut name.")
parser.add_argument(
"--num_proc",
default=None,
type=int,
help=
"Max number of processes when generating cache. Already cached shards are loaded sequentially."
)
parser.add_argument("--output_dir",
default="best_c3_model",
type=str,
help="The path of the checkpoints .")
parser.add_argument("--save_best_model",
default=True,
type=distutils.util.strtobool,
help="Whether to save best model.")
parser.add_argument("--overwrite_cache",
default=False,
type=distutils.util.strtobool,
help="Whether to overwrite cache for dataset.")
parser.add_argument("--num_train_epochs",
default=8,
type=int,
help="Total number of training epochs to perform.")
parser.add_argument("--weight_decay",
default=0.01,
type=float,
help="Weight decay if we apply some.")
parser.add_argument(
"--warmup_steps",
default=0,
type=int,
help=
"Linear warmup over warmup_steps. If > 0: Override warmup_proportion")
parser.add_argument("--warmup_proportion",
default=0.1,
type=float,
help="Linear warmup proportion over total steps.")
parser.add_argument(
"--max_steps",
default=-1,
type=int,
help=
"If > 0: set total number of training steps to perform. Override num_train_epochs."
)
parser.add_argument("--adam_epsilon",
default=1e-6,
type=float,
help="Epsilon for Adam optimizer.")
parser.add_argument("--learning_rate",
default=2e-5,
type=float,
help="The initial learning rate for Adam.")
parser.add_argument("--seed",
default=42,
type=int,
help="random seed for initialization")
parser.add_argument("--max_grad_norm",
default=1.0,
type=float,
help="The max value of grad norm.")
parser.add_argument("--batch_size",
default=24,
type=int,
help="Batch size per GPU/CPU for training.")
parser.add_argument("--eval_batch_size",
default=32,
type=int,
help="Batch size per GPU/CPU for training.")
parser.add_argument(
'--gradient_accumulation_steps',
type=int,
default=4,
help=
"Number of updates steps to accumualte before performing a backward/update pass."
)
parser.add_argument("--do_train",
action='store_true',
help="Whether to train.")
parser.add_argument("--do_predict",
action='store_true',
help="Whether to predict.")
parser.add_argument(
"--max_seq_length",
default=512,
type=int,
help=
"The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded.")
parser.add_argument("--logging_steps",
type=int,
default=100,
help="Log every X updates steps.")
args = parser.parse_args()
return args
def set_seed(args):
# Use the same data seed(for data shuffle) for all procs to guarantee data
# consistency after sharding.
random.seed(args.seed)
np.random.seed(args.seed)
# Maybe different op seeds(for dropout) for different procs is better. By:
# `paddle.seed(args.seed + paddle.distributed.get_rank())`
paddle.seed(args.seed)
@paddle.no_grad()
def evaluate(model, loss_fct, dev_data_loader, metric):
metric.reset()
model.eval()
for step, batch in enumerate(dev_data_loader):
input_ids, segment_ids, label_id = batch
logits = model(input_ids=input_ids, token_type_ids=segment_ids)
loss = loss_fct(logits, label_id)
correct = metric.compute(logits, label_id)
metric.update(correct)
acc = metric.accumulate()
model.train()
return acc
@contextlib.contextmanager
def main_process_first(desc="work"):
if paddle.distributed.get_world_size() > 1:
rank = paddle.distributed.get_rank()
is_main_process = rank == 0
main_process_desc = "main local process"
try:
if not is_main_process:
# tell all replicas to wait
logger.debug(
f"{rank}: waiting for the {main_process_desc} to perform {desc}"
)
paddle.distributed.barrier()
yield
finally:
if is_main_process:
# the wait is over
logger.debug(
f"{rank}: {main_process_desc} completed {desc}, releasing all replicas"
)
paddle.distributed.barrier()
else:
yield
def run(args):
if args.do_train:
assert args.batch_size % args.gradient_accumulation_steps == 0, \
"Please make sure argmument `batch_size` must be divisible by `gradient_accumulation_steps`."
max_seq_length = args.max_seq_length
max_num_choices = 4
def preprocess_function(examples, do_predict=False):
def _truncate_seq_tuple(tokens_a, tokens_b, tokens_c, max_length):
"""Truncates a sequence tuple in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer
# sequence one token at a time. This makes more sense than
# truncating an equal percent of tokens from each, since if one
# sequence is very short then each token that's truncated likely
# contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b) + len(tokens_c)
if total_length <= max_length:
break
if len(tokens_a) >= len(tokens_b) and len(tokens_a) >= len(
tokens_c):
tokens_a.pop()
elif len(tokens_b) >= len(tokens_a) and len(tokens_b) >= len(
tokens_c):
tokens_b.pop()
else:
tokens_c.pop()
num_examples = len(examples.data["question"])
if do_predict:
result = {"input_ids": [], "token_type_ids": []}
else:
result = {"input_ids": [], "token_type_ids": [], "labels": []}
for idx in range(num_examples):
text = '\n'.join(examples.data["context"][idx]).lower()
question = examples.data["question"][idx].lower()
choice_list = examples.data["choice"][idx]
choice_list = [choice.lower()
for choice in choice_list][:max_num_choices]
if not do_predict:
answer = examples.data["answer"][idx].lower()
label = choice_list.index(answer)
tokens_t = tokenizer.tokenize(text)
tokens_q = tokenizer.tokenize(question)
tokens_t_list = []
tokens_c_list = []
# Pad each new example for axis=1, [batch_size, num_choices, seq_len]
while len(choice_list) < max_num_choices:
choice_list.append('无效答案')
for choice in choice_list:
tokens_c = tokenizer.tokenize(choice.lower())
_truncate_seq_tuple(tokens_t, tokens_q, tokens_c,
max_seq_length - 4)
tokens_c = tokens_q + ["[SEP]"] + tokens_c
tokens_t_list.append(tokens_t)
tokens_c_list.append(tokens_c)
new_data = tokenizer(tokens_t_list,
text_pair=tokens_c_list,
is_split_into_words=True)
# Pad each new example for axis=2 of [batch_size, num_choices, seq_len],
# because length of each choice could be different.
input_ids = Pad(axis=0, pad_val=tokenizer.pad_token_id)(
new_data["input_ids"])
token_type_ids = Pad(axis=0, pad_val=tokenizer.pad_token_id)(
new_data["token_type_ids"])
# Final shape of input_ids: [batch_size, num_choices, seq_len]
result["input_ids"].append(input_ids)
result["token_type_ids"].append(token_type_ids)
if not do_predict:
result["labels"].append([label])
if (idx + 1) % 1000 == 0:
logger.info("%d samples have been processed." % (idx + 1))
return result
paddle.set_device(args.device)
set_seed(args)
if paddle.distributed.get_world_size() > 1:
paddle.distributed.init_parallel_env()
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
model = AutoModelForMultipleChoice.from_pretrained(
args.model_name_or_path, num_choices=max_num_choices)
if paddle.distributed.get_world_size() > 1:
model = paddle.DataParallel(model)
train_ds, dev_ds, test_ds = load_dataset(
"clue", "c3", split=["train", "validation", "test"])
if args.do_train:
args.batch_size = int(args.batch_size /
args.gradient_accumulation_steps)
column_names = train_ds.column_names
with main_process_first(desc="train dataset map pre-processing"):
train_ds = train_ds.map(
preprocess_function,
batched=True,
batch_size=len(train_ds),
num_proc=args.num_proc,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc="Running tokenizer on train dataset")
batchify_fn = lambda samples, fn=Dict({
'input_ids':
Pad(axis=1, pad_val=tokenizer.pad_token_id), # input
'token_type_ids':
Pad(axis=1, pad_val=tokenizer.pad_token_type_id), # segment
'labels':
Stack(dtype="int64") # label
}): fn(samples)
train_batch_sampler = paddle.io.DistributedBatchSampler(
train_ds, batch_size=args.batch_size, shuffle=True)
train_data_loader = paddle.io.DataLoader(
dataset=train_ds,
batch_sampler=train_batch_sampler,
collate_fn=batchify_fn,
num_workers=0,
return_list=True)
with main_process_first(desc="evaluate dataset map pre-processing"):
dev_ds = dev_ds.map(preprocess_function,
batched=True,
batch_size=len(dev_ds),
remove_columns=column_names,
num_proc=args.num_proc,
load_from_cache_file=args.overwrite_cache,
desc="Running tokenizer on validation dataset")
dev_batch_sampler = paddle.io.BatchSampler(
dev_ds, batch_size=args.eval_batch_size, shuffle=False)
dev_data_loader = paddle.io.DataLoader(dataset=dev_ds,
batch_sampler=dev_batch_sampler,
collate_fn=batchify_fn,
return_list=True)
num_training_steps = int(
args.max_steps /
args.gradient_accumulation_steps) if args.max_steps >= 0 else int(
len(train_data_loader) * args.num_train_epochs /
args.gradient_accumulation_steps)
warmup = args.warmup_steps if args.warmup_steps > 0 else args.warmup_proportion
lr_scheduler = LinearDecayWithWarmup(args.learning_rate,
num_training_steps, warmup)
# Generate parameter names needed to perform weight decay.
# All bias and LayerNorm parameters are excluded.
decay_params = [
p.name for n, p in model.named_parameters()
if not any(nd in n for nd in ["bias", "norm"])
]
grad_clip = paddle.nn.ClipGradByGlobalNorm(args.max_grad_norm)
optimizer = paddle.optimizer.AdamW(
learning_rate=lr_scheduler,
parameters=model.parameters(),
weight_decay=args.weight_decay,
apply_decay_param_fun=lambda x: x in decay_params,
grad_clip=grad_clip)
loss_fct = paddle.nn.loss.CrossEntropyLoss()
metric = paddle.metric.Accuracy()
model.train()
global_step = 0
best_acc = 0.0
tic_train = time.time()
for epoch in range(args.num_train_epochs):
for step, batch in enumerate(train_data_loader):
input_ids, segment_ids, label = batch
logits = model(input_ids=input_ids, token_type_ids=segment_ids)
loss = loss_fct(logits, label)
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
loss.backward()
if (step + 1) % args.gradient_accumulation_steps == 0:
global_step += 1
optimizer.step()
lr_scheduler.step()
optimizer.clear_grad()
if global_step % args.logging_steps == 0:
logger.info(
"global step %d/%d, epoch: %d, batch: %d, rank_id: %s, loss: %f, lr: %.10f, speed: %.4f step/s"
% (global_step, num_training_steps, epoch, step + 1,
paddle.distributed.get_rank(), loss,
optimizer.get_lr(), args.logging_steps /
(time.time() - tic_train)))
tic_train = time.time()
if global_step >= num_training_steps:
break
if global_step > num_training_steps:
break
tic_eval = time.time()
acc = evaluate(model, loss_fct, dev_data_loader, metric)
logger.info("eval acc: %.5f, eval done total : %s s" %
(acc, time.time() - tic_eval))
if paddle.distributed.get_rank() == 0 and acc > best_acc:
best_acc = acc
if args.save_best_model:
model_to_save = model._layers if isinstance(
model, paddle.DataParallel) else model
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
model_to_save.save_pretrained(args.output_dir)
tokenizer.save_pretrained(args.output_dir)
if global_step >= num_training_steps:
break
logger.info("best_result: %.2f" % (best_acc * 100))
if args.do_predict:
column_names = test_ds.column_names
test_ds = test_ds.map(partial(preprocess_function, do_predict=True),
batched=True,
batch_size=len(test_ds),
remove_columns=column_names,
num_proc=args.num_proc)
# Serveral samples have more than four choices.
test_batch_sampler = paddle.io.BatchSampler(test_ds,
batch_size=1,
shuffle=False)
batchify_fn = lambda samples, fn=Dict({
'input_ids':
Pad(axis=1, pad_val=tokenizer.pad_token_id), # input
'token_type_ids':
Pad(axis=1, pad_val=tokenizer.pad_token_type_id), # segment
}): fn(samples)
test_data_loader = paddle.io.DataLoader(
dataset=test_ds,
batch_sampler=test_batch_sampler,
collate_fn=batchify_fn,
return_list=True)
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
f = open(os.path.join(args.output_dir, "c311_predict.json"), 'w')
result = {}
idx = 0
for step, batch in enumerate(test_data_loader):
input_ids, segment_ids = batch
with paddle.no_grad():
logits = model(input_ids, segment_ids)
preds = paddle.argmax(logits, axis=1).numpy().tolist()
for pred in preds:
result[str(idx)] = pred
j = json.dumps({"id": idx, "label": pred})
f.write(j + "\n")
idx += 1
def print_arguments(args):
"""print arguments"""
print('----------- Configuration Arguments -----------')
for arg, value in sorted(vars(args).items()):
print('%s: %s' % (arg, value))
print('------------------------------------------------')
if __name__ == "__main__":
args = parse_args()
print_arguments(args)
run(args)
| 19,140 | 39.987152 | 123 | py |
CLUE | CLUE-master/baselines/paddlenlp/mrc/run_cmrc2018.py | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import random
import time
import json
import math
import distutils.util
import argparse
import contextlib
from functools import partial
import numpy as np
import paddle
from paddle.io import DataLoader
from paddlenlp.data import DataCollatorWithPadding
from paddlenlp.transformers import AutoModelForQuestionAnswering, AutoTokenizer
from paddlenlp.transformers import LinearDecayWithWarmup
from paddlenlp.metrics.squad import squad_evaluate, compute_prediction
from paddlenlp.utils.log import logger
from datasets import load_dataset
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--model_name_or_path",
default=None,
type=str,
required=True,
help="Path to pre-trained model or shortcut name of model.")
parser.add_argument(
"--output_dir",
default="best_cmrc_model",
type=str,
help=
"The output directory where the model predictions and checkpoints will be written."
)
parser.add_argument("--save_best_model",
default=True,
type=distutils.util.strtobool,
help="Whether to save best model.")
parser.add_argument("--overwrite_cache",
default=False,
type=distutils.util.strtobool,
help="Whether to overwrite cache for dataset.")
parser.add_argument(
"--max_seq_length",
default=128,
type=int,
help=
"The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded.")
parser.add_argument("--batch_size",
default=8,
type=int,
help="Batch size per GPU/CPU for training.")
parser.add_argument(
"--num_proc",
default=None,
type=int,
help=
"Max number of processes when generating cache. Already cached shards are loaded sequentially."
)
parser.add_argument("--eval_batch_size",
default=12,
type=int,
help="Batch size per GPU/CPU for training.")
parser.add_argument("--learning_rate",
default=5e-5,
type=float,
help="The initial learning rate for Adam.")
parser.add_argument("--weight_decay",
default=0.01,
type=float,
help="Weight decay if we apply some.")
parser.add_argument("--adam_epsilon",
default=1e-8,
type=float,
help="Epsilon for Adam optimizer.")
parser.add_argument("--max_grad_norm",
default=1.0,
type=float,
help="Max gradient norm.")
parser.add_argument("--num_train_epochs",
default=3,
type=int,
help="Total number of training epochs to perform.")
parser.add_argument(
"--max_steps",
default=-1,
type=int,
help=
"If > 0: set total number of training steps to perform. Override num_train_epochs."
)
parser.add_argument(
"--warmup_steps",
default=0,
type=int,
help=
"Linear warmup over warmup_steps. If > 0: Override warmup_proportion")
parser.add_argument(
"--warmup_proportion",
default=0.1,
type=float,
help=
"Proportion of training steps to perform linear learning rate warmup for."
)
parser.add_argument("--logging_steps",
type=int,
default=100,
help="Log every X updates steps.")
parser.add_argument("--seed",
type=int,
default=42,
help="random seed for initialization")
parser.add_argument(
'--device',
choices=['cpu', 'gpu'],
default="gpu",
help="Select which device to train model, defaults to gpu.")
parser.add_argument(
"--doc_stride",
type=int,
default=128,
help=
"When splitting up a long document into chunks, how much stride to take between chunks."
)
parser.add_argument(
"--n_best_size",
type=int,
default=20,
help=
"The total number of n-best predictions to generate in the nbest_predictions.json output file."
)
parser.add_argument("--max_query_length",
type=int,
default=64,
help="Max query length.")
parser.add_argument("--max_answer_length",
type=int,
default=50,
help="Max answer length.")
parser.add_argument(
"--do_lower_case",
action='store_false',
help=
"Whether to lower case the input text. Should be True for uncased models and False for cased models."
)
parser.add_argument("--verbose",
action='store_true',
help="Whether to output verbose log.")
parser.add_argument("--do_train",
action='store_true',
help="Whether to train.")
parser.add_argument("--do_predict",
action='store_true',
help="Whether to predict.")
parser.add_argument(
'--gradient_accumulation_steps',
type=int,
default=2,
help=
"Number of updates steps to accumualte before performing a backward/update pass."
)
args = parser.parse_args()
return args
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
paddle.seed(args.seed)
@paddle.no_grad()
def evaluate(model, raw_dataset, dataset, data_loader, args, do_eval=True):
model.eval()
all_start_logits = []
all_end_logits = []
tic_eval = time.time()
for batch in data_loader:
start_logits, end_logits = model(**batch)
for idx in range(start_logits.shape[0]):
if len(all_start_logits) % 1000 == 0 and len(all_start_logits):
logger.info("Processing example: %d" % len(all_start_logits))
logger.info('time per 1000: %s' % (time.time() - tic_eval))
tic_eval = time.time()
all_start_logits.append(start_logits.numpy()[idx])
all_end_logits.append(end_logits.numpy()[idx])
all_predictions, _, _ = compute_prediction(
raw_dataset, dataset, (all_start_logits, all_end_logits), False,
args.n_best_size, args.max_answer_length)
mode = 'validation' if do_eval else 'test'
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
if do_eval:
filename = os.path.join(args.output_dir, 'prediction_validation.json')
else:
filename = os.path.join(args.output_dir, 'cmrc2018_predict.json')
with open(filename, "w", encoding='utf-8') as writer:
writer.write(
json.dumps(all_predictions, ensure_ascii=False, indent=4) + "\n")
if do_eval:
res = squad_evaluate(examples=[raw_data for raw_data in raw_dataset],
preds=all_predictions,
is_whitespace_splited=False)
model.train()
return res['exact'], res['f1']
model.train()
class CrossEntropyLossForSQuAD(paddle.nn.Layer):
def __init__(self):
super(CrossEntropyLossForSQuAD, self).__init__()
def forward(self, y, label):
start_logits, end_logits = y
start_position, end_position = label
start_position = paddle.unsqueeze(start_position, axis=-1)
end_position = paddle.unsqueeze(end_position, axis=-1)
start_loss = paddle.nn.functional.cross_entropy(input=start_logits,
label=start_position)
end_loss = paddle.nn.functional.cross_entropy(input=end_logits,
label=end_position)
loss = (start_loss + end_loss) / 2
return loss
@contextlib.contextmanager
def main_process_first(desc="work"):
if paddle.distributed.get_world_size() > 1:
rank = paddle.distributed.get_rank()
is_main_process = rank == 0
main_process_desc = "main local process"
try:
if not is_main_process:
# tell all replicas to wait
logger.debug(
f"{rank}: waiting for the {main_process_desc} to perform {desc}"
)
paddle.distributed.barrier()
yield
finally:
if is_main_process:
# the wait is over
logger.debug(
f"{rank}: {main_process_desc} completed {desc}, releasing all replicas"
)
paddle.distributed.barrier()
else:
yield
def run(args):
if args.do_train:
assert args.batch_size % args.gradient_accumulation_steps == 0, \
"Please make sure argmument `batch_size` must be divisible by `gradient_accumulation_steps`."
paddle.set_device(args.device)
if paddle.distributed.get_world_size() > 1:
paddle.distributed.init_parallel_env()
rank = paddle.distributed.get_rank()
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
set_seed(args)
train_examples, dev_examples, test_examples = load_dataset(
'clue', 'cmrc2018', split=["train", "validation", "test"])
column_names = train_examples.column_names
if rank == 0:
if os.path.exists(args.model_name_or_path):
logger.info("init checkpoint from %s" % args.model_name_or_path)
model = AutoModelForQuestionAnswering.from_pretrained(
args.model_name_or_path)
if paddle.distributed.get_world_size() > 1:
model = paddle.DataParallel(model)
def prepare_train_features(examples):
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
# NOTE: Almost the same functionality as HuggingFace's prepare_train_features function. The main difference is
# that HugggingFace uses ArrowTable as basic data structure, while we use list of dictionary instead.
contexts = examples['context']
questions = examples['question']
tokenized_examples = tokenizer(questions,
contexts,
stride=args.doc_stride,
max_seq_len=args.max_seq_length)
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
sample_mapping = tokenized_examples.pop("overflow_to_sample")
# The offset mappings will give us a map from token to character position in the original context. This will
# help us compute the start_positions and end_positions.
offset_mapping = tokenized_examples.pop("offset_mapping")
# Let's label those examples!
tokenized_examples["start_positions"] = []
tokenized_examples["end_positions"] = []
for i, offsets in enumerate(offset_mapping):
# We will label impossible answers with the index of the CLS token.
input_ids = tokenized_examples["input_ids"][i]
cls_index = input_ids.index(tokenizer.cls_token_id)
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
sequence_ids = tokenized_examples['token_type_ids'][i]
# One example can give several spans, this is the index of the example containing this span of text.
sample_index = sample_mapping[i]
answers = examples['answers'][sample_index]
# If no answers are given, set the cls_index as answer.
if len(answers["answer_start"]) == 0:
tokenized_examples["start_positions"].append(cls_index)
tokenized_examples["end_positions"].append(cls_index)
else:
# Start/end character index of the answer in the text.
start_char = answers["answer_start"][0]
end_char = start_char + len(answers["text"][0])
# Start token index of the current span in the text.
token_start_index = 0
while sequence_ids[token_start_index] != 1:
token_start_index += 1
# End token index of the current span in the text.
token_end_index = len(input_ids) - 1
while sequence_ids[token_end_index] != 1:
token_end_index -= 1
token_end_index -= 1
# Detect if the answer is out of the span (in which case this feature is labeled with the CLS index).
if not (offsets[token_start_index][0] <= start_char
and offsets[token_end_index][1] >= end_char):
tokenized_examples["start_positions"].append(cls_index)
tokenized_examples["end_positions"].append(cls_index)
else:
# Otherwise move the token_start_index and token_end_index to the two ends of the answer.
# Note: we could go after the last offset if the answer is the last word (edge case).
while token_start_index < len(offsets) and offsets[
token_start_index][0] <= start_char:
token_start_index += 1
tokenized_examples["start_positions"].append(
token_start_index - 1)
while offsets[token_end_index][1] >= end_char:
token_end_index -= 1
tokenized_examples["end_positions"].append(token_end_index +
1)
return tokenized_examples
def prepare_validation_features(examples):
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
#NOTE: Almost the same functionality as HuggingFace's prepare_train_features function. The main difference is
# that HuggingFace uses ArrowTable as basic data structure, while we use list of dictionary instead.
contexts = examples['context']
questions = examples['question']
tokenized_examples = tokenizer(questions,
contexts,
stride=args.doc_stride,
max_seq_len=args.max_seq_length,
return_attention_mask=True)
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
sample_mapping = tokenized_examples.pop("overflow_to_sample")
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
tokenized_examples["example_id"] = []
for i in range(len(tokenized_examples["input_ids"])):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
sequence_ids = tokenized_examples['token_type_ids'][i]
context_index = 1
# One example can give several spans, this is the index of the example containing this span of text.
sample_index = sample_mapping[i]
tokenized_examples["example_id"].append(
examples["id"][sample_index])
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
tokenized_examples["offset_mapping"][i] = [
(o if sequence_ids[k] == context_index
and k != len(sequence_ids) - 1 else None)
for k, o in enumerate(tokenized_examples["offset_mapping"][i])
]
return tokenized_examples
if args.do_train:
args.batch_size = int(args.batch_size /
args.gradient_accumulation_steps)
with main_process_first(desc="train dataset map pre-processing"):
train_ds = train_examples.map(
prepare_train_features,
batched=True,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
num_proc=args.num_proc,
desc="Running tokenizer on train dataset")
train_batch_sampler = paddle.io.DistributedBatchSampler(
train_ds, batch_size=args.batch_size, shuffle=True)
batchify_fn = DataCollatorWithPadding(tokenizer)
train_data_loader = DataLoader(dataset=train_ds,
batch_sampler=train_batch_sampler,
collate_fn=batchify_fn,
return_list=True)
with main_process_first(desc="evaluate dataset map pre-processing"):
dev_ds = dev_examples.map(
prepare_validation_features,
batched=True,
remove_columns=column_names,
num_proc=args.num_proc,
load_from_cache_file=args.overwrite_cache,
desc="Running tokenizer on validation dataset")
dev_ds_for_model = dev_ds.remove_columns(
["example_id", "offset_mapping", "attention_mask"])
dev_batch_sampler = paddle.io.BatchSampler(
dev_ds, batch_size=args.eval_batch_size, shuffle=False)
dev_data_loader = DataLoader(dataset=dev_ds_for_model,
batch_sampler=dev_batch_sampler,
collate_fn=batchify_fn,
return_list=True)
num_training_steps = int(
args.max_steps /
args.gradient_accumulation_steps) if args.max_steps >= 0 else int(
len(train_data_loader) * args.num_train_epochs /
args.gradient_accumulation_steps)
warmup = args.warmup_steps if args.warmup_steps > 0 else args.warmup_proportion
lr_scheduler = LinearDecayWithWarmup(args.learning_rate,
num_training_steps, warmup)
# Generate parameter names needed to perform weight decay.
# All bias and LayerNorm parameters are excluded.
decay_params = [
p.name for n, p in model.named_parameters()
if not any(nd in n for nd in ["bias", "norm"])
]
optimizer = paddle.optimizer.AdamW(
learning_rate=lr_scheduler,
epsilon=args.adam_epsilon,
parameters=model.parameters(),
weight_decay=args.weight_decay,
apply_decay_param_fun=lambda x: x in decay_params)
criterion = CrossEntropyLossForSQuAD()
best_res = (0.0, 0.0)
global_step = 0
tic_train = time.time()
for epoch in range(args.num_train_epochs):
for step, batch in enumerate(train_data_loader):
start_positions = batch.pop("start_positions")
end_positions = batch.pop("end_positions")
logits = model(**batch)
loss = criterion(logits, (start_positions, end_positions))
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
loss.backward()
if (step + 1) % args.gradient_accumulation_steps == 0:
global_step += 1
optimizer.step()
lr_scheduler.step()
optimizer.clear_grad()
if global_step % args.logging_steps == 0:
logger.info(
"global step %d/%d, epoch: %d, batch: %d, loss: %f, speed: %.2f step/s"
% (global_step, num_training_steps, epoch, step + 1,
loss, args.logging_steps /
(time.time() - tic_train)))
tic_train = time.time()
if global_step >= num_training_steps:
break
if global_step > num_training_steps:
break
em, f1 = evaluate(model, dev_examples, dev_ds, dev_data_loader,
args)
if paddle.distributed.get_rank() == 0 and em > best_res[0]:
best_res = (em, f1)
if args.save_best_model:
output_dir = args.output_dir
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# need better way to get inner model of DataParallel
model_to_save = model._layers if isinstance(
model, paddle.DataParallel) else model
model_to_save.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)
if global_step >= num_training_steps:
break
logger.info("best_result: %.2f/%.2f" % (best_res[0], best_res[1]))
if args.do_predict and rank == 0:
test_ds = test_examples.map(prepare_validation_features,
batched=True,
remove_columns=column_names,
num_proc=args.num_proc)
test_ds_for_model = test_ds.remove_columns(
["example_id", "offset_mapping", "attention_mask"])
dev_batchify_fn = DataCollatorWithPadding(tokenizer)
test_batch_sampler = paddle.io.BatchSampler(
test_ds_for_model, batch_size=args.eval_batch_size, shuffle=False)
batchify_fn = DataCollatorWithPadding(tokenizer)
test_data_loader = DataLoader(dataset=test_ds_for_model,
batch_sampler=test_batch_sampler,
collate_fn=batchify_fn,
return_list=True)
evaluate(model,
test_examples,
test_ds,
test_data_loader,
args,
do_eval=False)
def print_arguments(args):
"""print arguments"""
print('----------- Configuration Arguments -----------')
for arg, value in sorted(vars(args).items()):
print('%s: %s' % (arg, value))
print('------------------------------------------------')
if __name__ == "__main__":
args = parse_args()
print_arguments(args)
run(args)
| 24,357 | 41.733333 | 118 | py |
CLUE | CLUE-master/baselines/paddlenlp/grid_search_tools/warmup_dataset_and_model.py | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
from paddlenlp.datasets import load_dataset
from paddlenlp.utils.log import logger
model_name_or_path = sys.argv[1]
# CLUE classification dataset warmup
logger.info("Download model and data for CLUE classification tasks.")
for task in [
"afqmc", "tnews", "iflytek", "ocnli", "cmnli", "cluewsc2020", "csl"
]:
load_dataset("clue", task, splits=("train", "dev", "test"))
# Downloads HF dataset
from datasets import load_dataset
load_dataset("clue", "chid")
load_dataset("clue", "cmrc2018")
load_dataset("clue", "c3")
# HF dataset process and cache
logger.info(
"Data process for CHID tasks, and this will take some time. If cache exists, this will skip."
)
status = os.system(
f"python ../mrc/run_chid.py --do_train --max_steps 0 --model_name_or_path {model_name_or_path} --batch_size 1 --gradient_accumulation_steps 1"
)
assert status == 0, "Please make sure clue dataset CHID has been preprocessed successfully."
logger.info("Data process for CMRC2018 tasks. If cache exists, this will skip.")
status = os.system(
f"python ../mrc/run_cmrc2018.py --do_train --max_steps 0 --model_name_or_path {model_name_or_path} --batch_size 1 --gradient_accumulation_steps 1"
)
assert status == 0, "Please make sure clue dataset CMRC2018 has been preprocessed successfully."
logger.info("Data process for C3 tasks. If cache exists, this will skip.")
status = os.system(
f"python ../mrc/run_c3.py --do_train --max_steps 0 --model_name_or_path {model_name_or_path} --batch_size 1 --gradient_accumulation_steps 1"
)
assert status == 0, "Please make sure clue dataset C3 has been preprocessed successfully."
| 2,253 | 40.740741 | 150 | py |
CLUE | CLUE-master/baselines/paddlenlp/grid_search_tools/grid_search.py | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import subprocess
import random
import sys
from collections import defaultdict
from pynvml import *
nvmlInit()
world_size = nvmlDeviceGetCount()
handles = []
mrc_device = {}
handle_mapping = {}
for i in range(world_size):
h = nvmlDeviceGetHandleByIndex(i)
handles.append(h)
handle_mapping[str(h)] = i
def get_availble(est=15, is_mrc=False):
# Sort handles according to info.free
handles.sort(key=lambda x: nvmlDeviceGetMemoryInfo(x).free, reverse=True)
for i, h in enumerate(handles):
device_id = handle_mapping[str(h)]
if device_id in mrc_device.values():
continue
info = nvmlDeviceGetMemoryInfo(h)
gb = 1024 * 1024 * 1024
print(f'- device_id: {device_id}')
print(f'- free : {info.free/gb}')
if info.free / gb >= est:
return device_id
return None
# TODO Support multi-machine
def get_mrc_tasks(model_name_or_path):
learning_rate_list = [1e-5, 2e-5, 3e-5]
batch_size_list = [32, 24]
cls_base_grd_acc = 4
tasks = []
for lr in learning_rate_list:
for bs in batch_size_list:
tasks.append(
f"bash run_mrc.sh {model_name_or_path} chid {bs} {lr} {cls_base_grd_acc*2}"
)
tasks.append(
f"bash run_mrc.sh {model_name_or_path} cmrc2018 {bs} {lr} {cls_base_grd_acc}"
)
tasks.append(
f"bash run_mrc.sh {model_name_or_path} c3 {bs} {lr} {bs//2}")
return tasks
def get_cls_tasks(model_name_or_path):
learning_rate_list = [1e-5, 2e-5, 3e-5, 5e-5]
batch_size_list = [16, 32, 64]
datasets = [
'afqmc', 'tnews', 'iflytek', 'ocnli', 'cmnli', 'cluewsc2020', 'csl'
]
cls_base_grd_acc = 1
hyper_params = {
"afqmc": [[3, 128, cls_base_grd_acc, 0.1]],
"tnews": [[3, 128, cls_base_grd_acc, 0.1]],
"iflytek": [[3, 128, cls_base_grd_acc, 0.1],
[3, 128, cls_base_grd_acc, 0.0]],
"ocnli": [[5, 128, cls_base_grd_acc, 0.1]],
"cluewsc2020": [[50, 128, cls_base_grd_acc, 0.1],
[50, 128, cls_base_grd_acc, 0.0]],
"csl": [[5, 256, cls_base_grd_acc * 2, 0.1]],
"cmnli": [[2, 128, cls_base_grd_acc, 0.1]]
}
tasks = []
for dataset in datasets:
for lr in learning_rate_list:
for bs in batch_size_list:
for hyper_param in hyper_params[dataset]:
epoch, max_seq_len, grd_acc, dropout = hyper_param
tasks.append(
f"bash run_cls.sh {dataset} {lr} {bs} {epoch} {max_seq_len} {model_name_or_path} {grd_acc} {dropout}"
)
for lr in learning_rate_list:
for hyper_param in hyper_params["cluewsc2020"]:
bs = 8
epoch, max_seq_len, grd_acc, dropout = hyper_param
tasks.append(
f"bash run_cls.sh cluewsc2020 {lr} {bs} {epoch} {max_seq_len} {model_name_or_path} {grd_acc} {dropout}"
)
return tasks
def do_task(task):
tmp = task.split(" ")
est = 15
# if int(tmp[4]) * int(tmp[6]) > 32 * 128:
# est = 30
print(est)
is_mrc = False
if "cmrc" in task or "chid" in task or "c3" in task:
is_mrc = True
device_id = get_availble(est, is_mrc)
retry = 5
while device_id is None and retry > 0:
print("> No device avaliable, wait 120 seconds.")
time.sleep(120)
device_id = get_availble(est, is_mrc)
retry -= 1
if retry == 0:
return None
task_ps = f"set -x \nexport CUDA_VISIBLE_DEVICES={device_id}\n" + task
print(f"> Send task \n{task_ps}\n")
ps = subprocess.Popen(task_ps,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
if is_mrc and device_id is not None:
mrc_device[task] = device_id
print("mrc_device", mrc_device)
return ps
def main():
model_name_or_path = sys.argv[1]
# Make sure that dataset has been downloaded first
status = os.system(
f"python warmup_dataset_and_model.py {model_name_or_path}")
assert status == 0, "Please make sure clue dataset has been downloaded successfully."
tasks = []
tasks = get_cls_tasks(model_name_or_path)
tasks += get_mrc_tasks(model_name_or_path)
for x in tasks:
print(x)
runs = []
retry = defaultdict(int)
while len(tasks) > 0 or len(runs) > 0:
i = 0
print("\n\n\n>> Round start")
while i < len(runs):
returncode = runs[i]["ps"].poll()
if returncode is not None:
if returncode != 0:
retry[runs[i]["ts"]] += 1
print(
f"> {runs[i]['ts']} task failed, will retried, tryed {retry[runs[i]['ts']]} times."
)
output = runs[i]["ps"].communicate()[0]
for line in output.decode('utf-8').split("\n"):
print(line)
if retry[runs[i]["ts"]] <= 5:
tasks.append(runs[i]["ts"])
else:
if "cmrc" in runs[i]["ts"] or "chid" in runs[i][
"ts"] or "c3" in runs[i]["ts"]:
mrc_device.pop(runs[i]['ts'])
print("mrc_device", mrc_device)
print(f"> Done! {runs[i]['ts']}")
runs.pop(i)
i = i - 1
else:
print(">> DOING", runs[i]["ts"])
i += 1
if len(tasks) > 0:
task = tasks.pop(0)
print(f"> Try to append {task}")
ps = do_task(task)
if ps is None:
tasks.append(task)
else:
runs.append({"ps": ps, "ts": task})
print(f"> Wait for 15 seconds to start!")
time.sleep(15)
print("All done!")
status = os.system(f'bash extract_result.sh {model_name_or_path}')
if __name__ == "__main__":
main()
| 6,743 | 32.889447 | 125 | py |
CLUE | CLUE-master/baselines/models/classifier_utils.py | # -*- coding: utf-8 -*-
# @Author: bo.shi
# @Date: 2019-12-01 22:28:41
# @Last Modified by: bo.shi
# @Last Modified time: 2019-12-02 18:36:50
# coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility functions for GLUE classification tasks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import csv
import os
import six
import tensorflow as tf
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text.decode("utf-8", "ignore")
elif isinstance(text, unicode):
return text
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?")
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
Only must be specified for sequence pair tasks.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.label = label
class PaddingInputExample(object):
"""Fake example so the num input examples is a multiple of the batch size.
When running eval/predict on the TPU, we need to pad the number of examples
to be a multiple of the batch size, because the TPU requires a fixed batch
size. The alternative is to drop the last batch, which is bad because it means
the entire output data won't be generated.
We use this class instead of `None` because treating `None` as padding
battches could cause silent errors.
"""
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_test_examples(self, data_dir):
"""Gets a collection of `InputExample`s for prediction."""
raise NotImplementedError()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
@classmethod
def _read_tsv(cls, input_file, delimiter="\t", quotechar=None):
"""Reads a tab separated value file."""
with tf.gfile.Open(input_file, "r") as f:
reader = csv.reader(f, delimiter=delimiter, quotechar=quotechar)
lines = []
for line in reader:
lines.append(line)
return lines
@classmethod
def _read_txt(cls, input_file):
"""Reads a tab separated value file."""
with tf.gfile.Open(input_file, "r") as f:
reader = f.readlines()
lines = []
for line in reader:
lines.append(line.strip().split("_!_"))
return lines
@classmethod
def _read_json(cls, input_file):
"""Reads a tab separated value file."""
with tf.gfile.Open(input_file, "r") as f:
reader = f.readlines()
lines = []
for line in reader:
lines.append(json.loads(line.strip()))
return lines
class XnliProcessor(DataProcessor):
"""Processor for the XNLI data set."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "train.json")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "dev.json")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "test.json")), "test")
def _create_examples(self, lines, set_type):
"""See base class."""
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text_a = convert_to_unicode(line['premise'])
text_b = convert_to_unicode(line['hypo'])
label = convert_to_unicode(line['label']) if set_type != 'test' else 'contradiction'
examples.append(
InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
def get_labels(self):
"""See base class."""
return ["contradiction", "entailment", "neutral"]
# class TnewsProcessor(DataProcessor):
# """Processor for the MRPC data set (GLUE version)."""
#
# def get_train_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "toutiao_category_train.txt")), "train")
#
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "toutiao_category_dev.txt")), "dev")
#
# def get_test_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "toutiao_category_test.txt")), "test")
#
# def get_labels(self):
# """See base class."""
# labels = []
# for i in range(17):
# if i == 5 or i == 11:
# continue
# labels.append(str(100 + i))
# return labels
#
# def _create_examples(self, lines, set_type):
# """Creates examples for the training and dev sets."""
# examples = []
# for (i, line) in enumerate(lines):
# if i == 0:
# continue
# guid = "%s-%s" % (set_type, i)
# text_a = convert_to_unicode(line[3])
# text_b = None
# label = convert_to_unicode(line[1])
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
# return examples
class TnewsProcessor(DataProcessor):
"""Processor for the MRPC data set (GLUE version)."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "train.json")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "dev.json")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "test.json")), "test")
def get_labels(self):
"""See base class."""
labels = []
for i in range(17):
if i == 5 or i == 11:
continue
labels.append(str(100 + i))
return labels
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text_a = convert_to_unicode(line['sentence'])
text_b = None
label = convert_to_unicode(line['label']) if set_type != 'test' else "100"
examples.append(
InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
# class iFLYTEKDataProcessor(DataProcessor):
# """Processor for the iFLYTEKData data set (GLUE version)."""
#
# def get_train_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "train.txt")), "train")
#
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "dev.txt")), "dev")
#
# def get_test_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "test.txt")), "test")
#
# def get_labels(self):
# """See base class."""
# labels = []
# for i in range(119):
# labels.append(str(i))
# return labels
#
# def _create_examples(self, lines, set_type):
# """Creates examples for the training and dev sets."""
# examples = []
# for (i, line) in enumerate(lines):
# if i == 0:
# continue
# guid = "%s-%s" % (set_type, i)
# text_a = convert_to_unicode(line[1])
# text_b = None
# label = convert_to_unicode(line[0])
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
# return examples
class iFLYTEKDataProcessor(DataProcessor):
"""Processor for the iFLYTEKData data set (GLUE version)."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "train.json")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "dev.json")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "test.json")), "test")
def get_labels(self):
"""See base class."""
labels = []
for i in range(119):
labels.append(str(i))
return labels
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text_a = convert_to_unicode(line['sentence'])
text_b = None
label = convert_to_unicode(line['label']) if set_type != 'test' else "0"
examples.append(
InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class AFQMCProcessor(DataProcessor):
"""Processor for the internal data set. sentence pair classification"""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "train.json")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "dev.json")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "test.json")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text_a = convert_to_unicode(line['sentence1'])
text_b = convert_to_unicode(line['sentence2'])
label = convert_to_unicode(line['label']) if set_type != 'test' else '0'
examples.append(
InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class CMNLIProcessor(DataProcessor):
"""Processor for the CMNLI data set."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples_json(os.path.join(data_dir, "train.json"), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples_json(os.path.join(data_dir, "dev.json"), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples_json(os.path.join(data_dir, "test.json"), "test")
def get_labels(self):
"""See base class."""
return ["contradiction", "entailment", "neutral"]
def _create_examples_json(self, file_name, set_type):
"""Creates examples for the training and dev sets."""
examples = []
lines = tf.gfile.Open(file_name, "r")
index = 0
for line in lines:
line_obj = json.loads(line)
index = index + 1
guid = "%s-%s" % (set_type, index)
text_a = convert_to_unicode(line_obj["sentence1"])
text_b = convert_to_unicode(line_obj["sentence2"])
label = convert_to_unicode(line_obj["label"]) if set_type != 'test' else 'neutral'
if label != "-":
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class CslProcessor(DataProcessor):
"""Processor for the CSL data set."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "train.json")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "dev.json")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "test.json")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text_a = convert_to_unicode(" ".join(line['keyword']))
text_b = convert_to_unicode(line['abst'])
label = convert_to_unicode(line['label']) if set_type != 'test' else '0'
examples.append(
InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
# class InewsProcessor(DataProcessor):
# """Processor for the MRPC data set (GLUE version)."""
#
# def get_train_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "train.txt")), "train")
#
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "dev.txt")), "dev")
#
# def get_test_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "test.txt")), "test")
#
# def get_labels(self):
# """See base class."""
# labels = ["0", "1", "2"]
# return labels
#
# def _create_examples(self, lines, set_type):
# """Creates examples for the training and dev sets."""
# examples = []
# for (i, line) in enumerate(lines):
# if i == 0:
# continue
# guid = "%s-%s" % (set_type, i)
# text_a = convert_to_unicode(line[2])
# text_b = convert_to_unicode(line[3])
# label = convert_to_unicode(line[0]) if set_type != "test" else '0'
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
# return examples
#
#
# class THUCNewsProcessor(DataProcessor):
# """Processor for the THUCNews data set (GLUE version)."""
#
# def get_train_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "train.txt")), "train")
#
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "dev.txt")), "dev")
#
# def get_test_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_txt(os.path.join(data_dir, "test.txt")), "test")
#
# def get_labels(self):
# """See base class."""
# labels = []
# for i in range(14):
# labels.append(str(i))
# return labels
#
# def _create_examples(self, lines, set_type):
# """Creates examples for the training and dev sets."""
# examples = []
# for (i, line) in enumerate(lines):
# if i == 0 or len(line) < 3:
# continue
# guid = "%s-%s" % (set_type, i)
# text_a = convert_to_unicode(line[3])
# text_b = None
# label = convert_to_unicode(line[0])
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
# return examples
#
# class LCQMCProcessor(DataProcessor):
# """Processor for the internal data set. sentence pair classification"""
#
# def __init__(self):
# self.language = "zh"
#
# def get_train_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "train.txt")), "train")
# # dev_0827.tsv
#
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "dev.txt")), "dev")
#
# def get_test_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "test.txt")), "test")
#
# def get_labels(self):
# """See base class."""
# return ["0", "1"]
# # return ["-1","0", "1"]
#
# def _create_examples(self, lines, set_type):
# """Creates examples for the training and dev sets."""
# examples = []
# print("length of lines:", len(lines))
# for (i, line) in enumerate(lines):
# # print('#i:',i,line)
# if i == 0:
# continue
# guid = "%s-%s" % (set_type, i)
# try:
# label = convert_to_unicode(line[2])
# text_a = convert_to_unicode(line[0])
# text_b = convert_to_unicode(line[1])
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
# except Exception:
# print('###error.i:', i, line)
# return examples
#
#
# class JDCOMMENTProcessor(DataProcessor):
# """Processor for the internal data set. sentence pair classification"""
#
# def __init__(self):
# self.language = "zh"
#
# def get_train_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "jd_train.csv"), ",", "\""), "train")
# # dev_0827.tsv
#
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "jd_dev.csv"), ",", "\""), "dev")
#
# def get_test_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "jd_test.csv"), ",", "\""), "test")
#
# def get_labels(self):
# """See base class."""
# return ["1", "2", "3", "4", "5"]
# # return ["-1","0", "1"]
#
# def _create_examples(self, lines, set_type):
# """Creates examples for the training and dev sets."""
# examples = []
# print("length of lines:", len(lines))
# for (i, line) in enumerate(lines):
# # print('#i:',i,line)
# if i == 0:
# continue
# guid = "%s-%s" % (set_type, i)
# try:
# label = convert_to_unicode(line[0])
# text_a = convert_to_unicode(line[1])
# text_b = convert_to_unicode(line[2])
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
# except Exception:
# print('###error.i:', i, line)
# return examples
#
#
# class BQProcessor(DataProcessor):
# """Processor for the internal data set. sentence pair classification"""
#
# def __init__(self):
# self.language = "zh"
#
# def get_train_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "train.txt")), "train")
# # dev_0827.tsv
#
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "dev.txt")), "dev")
#
# def get_test_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "test.txt")), "test")
#
# def get_labels(self):
# """See base class."""
# return ["0", "1"]
# # return ["-1","0", "1"]
#
# def _create_examples(self, lines, set_type):
# """Creates examples for the training and dev sets."""
# examples = []
# print("length of lines:", len(lines))
# for (i, line) in enumerate(lines):
# # print('#i:',i,line)
# if i == 0:
# continue
# guid = "%s-%s" % (set_type, i)
# try:
# label = convert_to_unicode(line[2])
# text_a = convert_to_unicode(line[0])
# text_b = convert_to_unicode(line[1])
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
# except Exception:
# print('###error.i:', i, line)
# return examples
#
#
# class MnliProcessor(DataProcessor):
# """Processor for the MultiNLI data set (GLUE version)."""
#
# def get_train_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
#
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")),
# "dev_matched")
#
# def get_test_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test")
#
# def get_labels(self):
# """See base class."""
# return ["contradiction", "entailment", "neutral"]
#
# def _create_examples(self, lines, set_type):
# """Creates examples for the training and dev sets."""
# examples = []
# for (i, line) in enumerate(lines):
# if i == 0:
# continue
# guid = "%s-%s" % (set_type, convert_to_unicode(line[0]))
# text_a = convert_to_unicode(line[8])
# text_b = convert_to_unicode(line[9])
# if set_type == "test":
# label = "contradiction"
# else:
# label = convert_to_unicode(line[-1])
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
# return examples
#
#
# class MrpcProcessor(DataProcessor):
# """Processor for the MRPC data set (GLUE version)."""
#
# def get_train_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
#
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
#
# def get_test_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
#
# def get_labels(self):
# """See base class."""
# return ["0", "1"]
#
# def _create_examples(self, lines, set_type):
# """Creates examples for the training and dev sets."""
# examples = []
# for (i, line) in enumerate(lines):
# if i == 0:
# continue
# guid = "%s-%s" % (set_type, i)
# text_a = convert_to_unicode(line[3])
# text_b = convert_to_unicode(line[4])
# if set_type == "test":
# label = "0"
# else:
# label = convert_to_unicode(line[0])
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
# return examples
#
#
# class ColaProcessor(DataProcessor):
# """Processor for the CoLA data set (GLUE version)."""
#
# def get_train_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
#
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
#
# def get_test_examples(self, data_dir):
# """See base class."""
# return self._create_examples(
# self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
#
# def get_labels(self):
# """See base class."""
# return ["0", "1"]
#
# def _create_examples(self, lines, set_type):
# """Creates examples for the training and dev sets."""
# examples = []
# for (i, line) in enumerate(lines):
# # Only the test set has a header
# if set_type == "test" and i == 0:
# continue
# guid = "%s-%s" % (set_type, i)
# if set_type == "test":
# text_a = convert_to_unicode(line[1])
# label = "0"
# else:
# text_a = convert_to_unicode(line[3])
# label = convert_to_unicode(line[1])
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
# return examples
class WSCProcessor(DataProcessor):
"""Processor for the internal data set. sentence pair classification"""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "train.json")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "dev.json")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "test.json")), "test")
def get_labels(self):
"""See base class."""
return ["true", "false"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text_a = convert_to_unicode(line['text'])
text_a_list = list(text_a)
target = line['target']
query = target['span1_text']
query_idx = target['span1_index']
pronoun = target['span2_text']
pronoun_idx = target['span2_index']
assert text_a[pronoun_idx: (pronoun_idx + len(pronoun))
] == pronoun, "pronoun: {}".format(pronoun)
assert text_a[query_idx: (query_idx + len(query))] == query, "query: {}".format(query)
if pronoun_idx > query_idx:
text_a_list.insert(query_idx, "_")
text_a_list.insert(query_idx + len(query) + 1, "_")
text_a_list.insert(pronoun_idx + 2, "[")
text_a_list.insert(pronoun_idx + len(pronoun) + 2 + 1, "]")
else:
text_a_list.insert(pronoun_idx, "[")
text_a_list.insert(pronoun_idx + len(pronoun) + 1, "]")
text_a_list.insert(query_idx + 2, "_")
text_a_list.insert(query_idx + len(query) + 2 + 1, "_")
text_a = "".join(text_a_list)
if set_type == "test":
label = "true"
else:
label = line['label']
examples.append(
InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
return examples
class COPAProcessor(DataProcessor):
"""Processor for the internal data set. sentence pair classification"""
def __init__(self):
self.language = "zh"
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "train.json")), "train")
# dev_0827.tsv
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "dev.json")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "test.json")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
@classmethod
def _create_examples_one(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
guid1 = "%s-%s" % (set_type, i)
# try:
if line['question'] == 'cause':
text_a = convert_to_unicode(line['premise'] + '原因是什么呢?' + line['choice0'])
text_b = convert_to_unicode(line['premise'] + '原因是什么呢?' + line['choice1'])
else:
text_a = convert_to_unicode(line['premise'] + '造成了什么影响呢?' + line['choice0'])
text_b = convert_to_unicode(line['premise'] + '造成了什么影响呢?' + line['choice1'])
label = convert_to_unicode(str(1 if line['label'] == 0 else 0)) if set_type != 'test' else '0'
examples.append(
InputExample(guid=guid1, text_a=text_a, text_b=text_b, label=label))
# except Exception as e:
# print('###error.i:',e, i, line)
return examples
@classmethod
def _create_examples(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
i = 2 * i
guid1 = "%s-%s" % (set_type, i)
guid2 = "%s-%s" % (set_type, i + 1)
# try:
premise = convert_to_unicode(line['premise'])
choice0 = convert_to_unicode(line['choice0'])
label = convert_to_unicode(str(1 if line['label'] == 0 else 0)) if set_type != 'test' else '0'
#text_a2 = convert_to_unicode(line['premise'])
choice1 = convert_to_unicode(line['choice1'])
label2 = convert_to_unicode(
str(0 if line['label'] == 0 else 1)) if set_type != 'test' else '0'
if line['question'] == 'effect':
text_a = premise
text_b = choice0
text_a2 = premise
text_b2 = choice1
elif line['question'] == 'cause':
text_a = choice0
text_b = premise
text_a2 = choice1
text_b2 = premise
else:
print('wrong format!!')
return None
examples.append(
InputExample(guid=guid1, text_a=text_a, text_b=text_b, label=label))
examples.append(
InputExample(guid=guid2, text_a=text_a2, text_b=text_b2, label=label2))
# except Exception as e:
# print('###error.i:',e, i, line)
return examples
| 31,044 | 32.707926 | 100 | py |
CLUE | CLUE-master/baselines/models/xlnet/cmrc2018_evaluate_drcd.py | # -*- coding: utf-8 -*-
'''
Evaluation script for CMRC 2018
version: v5
Note:
v5 formatted output, add usage description
v4 fixed segmentation issues
'''
from __future__ import print_function
from collections import Counter, OrderedDict
import string
import re
import argparse
import json
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import nltk
import pdb
# split Chinese with English
def mixed_segmentation(in_str, rm_punc=False):
in_str = str(in_str).decode('utf-8').lower().strip()
segs_out = []
temp_str = ""
sp_char = ['-',':','_','*','^','/','\\','~','`','+','=',
',','。',':','?','!','“','”',';','’','《','》','……','·','、',
'「','」','(',')','-','~','『','』']
for char in in_str:
if rm_punc and char in sp_char:
continue
if re.search(ur'[\u4e00-\u9fa5]', char) or char in sp_char:
if temp_str != "":
ss = nltk.word_tokenize(temp_str)
segs_out.extend(ss)
temp_str = ""
segs_out.append(char)
else:
temp_str += char
#handling last part
if temp_str != "":
ss = nltk.word_tokenize(temp_str)
segs_out.extend(ss)
return segs_out
# remove punctuation
def remove_punctuation(in_str):
in_str = str(in_str).decode('utf-8').lower().strip()
sp_char = ['-',':','_','*','^','/','\\','~','`','+','=',
',','。',':','?','!','“','”',';','’','《','》','……','·','、',
'「','」','(',')','-','~','『','』']
out_segs = []
for char in in_str:
if char in sp_char:
continue
else:
out_segs.append(char)
return ''.join(out_segs)
# find longest common string
def find_lcs(s1, s2):
m = [[0 for i in range(len(s2)+1)] for j in range(len(s1)+1)]
mmax = 0
p = 0
for i in range(len(s1)):
for j in range(len(s2)):
if s1[i] == s2[j]:
m[i+1][j+1] = m[i][j]+1
if m[i+1][j+1] > mmax:
mmax=m[i+1][j+1]
p=i+1
return s1[p-mmax:p], mmax
#
def evaluate(ground_truth_file, prediction_file):
f1 = 0
em = 0
total_count = 0
skip_count = 0
for instance in ground_truth_file["data"]:
#context_id = instance['context_id'].strip()
#context_text = instance['context_text'].strip()
for para in instance["paragraphs"]:
for qas in para['qas']:
total_count += 1
query_id = qas['id'].strip()
query_text = qas['question'].strip()
answers = [x["text"] for x in qas['answers']]
if query_id not in prediction_file:
sys.stderr.write('Unanswered question: {}\n'.format(query_id))
skip_count += 1
continue
prediction = str(prediction_file[query_id]).decode('utf-8')
f1 += calc_f1_score(answers, prediction)
em += calc_em_score(answers, prediction)
f1_score = 100.0 * f1 / total_count
em_score = 100.0 * em / total_count
return f1_score, em_score, total_count, skip_count
def calc_f1_score(answers, prediction):
f1_scores = []
for ans in answers:
ans_segs = mixed_segmentation(ans, rm_punc=True)
prediction_segs = mixed_segmentation(prediction, rm_punc=True)
lcs, lcs_len = find_lcs(ans_segs, prediction_segs)
if lcs_len == 0:
f1_scores.append(0)
continue
precision = 1.0*lcs_len/len(prediction_segs)
recall = 1.0*lcs_len/len(ans_segs)
f1 = (2*precision*recall)/(precision+recall)
f1_scores.append(f1)
return max(f1_scores)
def calc_em_score(answers, prediction):
em = 0
for ans in answers:
ans_ = remove_punctuation(ans)
prediction_ = remove_punctuation(prediction)
if ans_ == prediction_:
em = 1
break
return em
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Evaluation Script for CMRC 2018')
parser.add_argument('dataset_file', help='Official dataset file')
parser.add_argument('prediction_file', help='Your prediction File')
args = parser.parse_args()
ground_truth_file = json.load(open(args.dataset_file, 'rb'))
prediction_file = json.load(open(args.prediction_file, 'rb'))
F1, EM, TOTAL, SKIP = evaluate(ground_truth_file, prediction_file)
AVG = (EM+F1)*0.5
output_result = OrderedDict()
output_result['AVERAGE'] = '%.3f' % AVG
output_result['F1'] = '%.3f' % F1
output_result['EM'] = '%.3f' % EM
output_result['TOTAL'] = TOTAL
output_result['SKIP'] = SKIP
output_result['FILE'] = args.prediction_file
print(json.dumps(output_result))
| 4,169 | 26.434211 | 80 | py |
CLUE | CLUE-master/baselines/models/xlnet/run_classifier.py | # -*- coding: utf-8 -*-
# @Author: bo.shi
# @Date: 2019-11-04 09:56:36
# @Last Modified by: bo.shi
# @Last Modified time: 2019-12-04 14:39:31
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os.path import join
from absl import flags
import os
import sys
import csv
import collections
import numpy as np
import time
import math
import json
import random
from copy import copy
from collections import defaultdict as dd
import absl.logging as _logging # pylint: disable=unused-import
import tensorflow as tf
import sentencepiece as spm
from data_utils import SEP_ID, CLS_ID
import model_utils
import function_builder
from prepro_utils import preprocess_text, encode_ids
sys.path.append('..')
from classifier_utils import *
# Model
flags.DEFINE_string("model_config_path", default=None,
help="Model config path.")
flags.DEFINE_float("dropout", default=0.1,
help="Dropout rate.")
flags.DEFINE_float("dropatt", default=0.1,
help="Attention dropout rate.")
flags.DEFINE_integer("clamp_len", default=-1,
help="Clamp length")
flags.DEFINE_string("summary_type", default="last",
help="Method used to summarize a sequence into a compact vector.")
flags.DEFINE_bool("use_summ_proj", default=True,
help="Whether to use projection for summarizing sequences.")
flags.DEFINE_bool("use_bfloat16", False,
help="Whether to use bfloat16.")
# Parameter initialization
flags.DEFINE_enum("init", default="normal",
enum_values=["normal", "uniform"],
help="Initialization method.")
flags.DEFINE_float("init_std", default=0.02,
help="Initialization std when init is normal.")
flags.DEFINE_float("init_range", default=0.1,
help="Initialization std when init is uniform.")
# I/O paths
flags.DEFINE_bool("overwrite_data", default=False,
help="If False, will use cached data if available.")
flags.DEFINE_string("init_checkpoint", default=None,
help="checkpoint path for initializing the model. "
"Could be a pretrained model or a finetuned model.")
flags.DEFINE_string("output_dir", default="",
help="Output dir for TF records.")
flags.DEFINE_string("spiece_model_file", default="",
help="Sentence Piece model path.")
flags.DEFINE_string("model_dir", default="",
help="Directory for saving the finetuned model.")
flags.DEFINE_string("data_dir", default="",
help="Directory for input data.")
# TPUs and machines
flags.DEFINE_bool("use_tpu", default=False, help="whether to use TPU.")
flags.DEFINE_integer("num_hosts", default=1, help="How many TPU hosts.")
flags.DEFINE_integer("num_core_per_host", default=8,
help="8 for TPU v2 and v3-8, 16 for larger TPU v3 pod. In the context "
"of GPU training, it refers to the number of GPUs used.")
flags.DEFINE_string("tpu_job_name", default=None, help="TPU worker job name.")
flags.DEFINE_string("tpu", default=None, help="TPU name.")
flags.DEFINE_string("tpu_zone", default=None, help="TPU zone.")
flags.DEFINE_string("gcp_project", default=None, help="gcp project.")
flags.DEFINE_string("master", default=None, help="master")
flags.DEFINE_integer("iterations", default=1000,
help="number of iterations per TPU training loop.")
# training
flags.DEFINE_bool("do_train", default=False, help="whether to do training")
flags.DEFINE_integer("train_steps", default=1000,
help="Number of training steps")
flags.DEFINE_integer("num_train_epochs", default=0,
help="Number of training steps")
flags.DEFINE_integer("warmup_steps", default=0, help="number of warmup steps")
flags.DEFINE_float("learning_rate", default=1e-5, help="initial learning rate")
flags.DEFINE_float("lr_layer_decay_rate", 1.0,
"Top layer: lr[L] = FLAGS.learning_rate."
"Low layer: lr[l-1] = lr[l] * lr_layer_decay_rate.")
flags.DEFINE_float("min_lr_ratio", default=0.0,
help="min lr ratio for cos decay.")
flags.DEFINE_float("clip", default=1.0, help="Gradient clipping")
flags.DEFINE_integer("max_save", default=0,
help="Max number of checkpoints to save. Use 0 to save all.")
flags.DEFINE_integer("save_steps", default=None,
help="Save the model for every save_steps. "
"If None, not to save any model.")
flags.DEFINE_integer("train_batch_size", default=8,
help="Batch size for training")
flags.DEFINE_float("weight_decay", default=0.00, help="Weight decay rate")
flags.DEFINE_float("adam_epsilon", default=1e-8, help="Adam epsilon")
flags.DEFINE_string("decay_method", default="poly", help="poly or cos")
# evaluation
flags.DEFINE_bool("do_eval", default=False, help="whether to do eval")
flags.DEFINE_bool("do_predict", default=False, help="whether to do prediction")
flags.DEFINE_float("predict_threshold", default=0,
help="Threshold for binary prediction.")
flags.DEFINE_string("eval_split", default="dev", help="could be dev or test")
flags.DEFINE_integer("eval_batch_size", default=128,
help="batch size for evaluation")
flags.DEFINE_integer("predict_batch_size", default=128,
help="batch size for prediction.")
flags.DEFINE_string("predict_dir", default=None,
help="Dir for saving prediction files.")
flags.DEFINE_bool("eval_all_ckpt", default=False,
help="Eval all ckpts. If False, only evaluate the last one.")
flags.DEFINE_string("predict_ckpt", default=None,
help="Ckpt path for do_predict. If None, use the last one.")
# task specific
flags.DEFINE_string("task_name", default=None, help="Task name")
flags.DEFINE_integer("max_seq_length", default=128, help="Max sequence length")
flags.DEFINE_integer("shuffle_buffer", default=2048,
help="Buffer size used for shuffle.")
flags.DEFINE_integer("num_passes", default=1,
help="Num passes for processing training data. "
"This is use to batch data without loss for TPUs.")
flags.DEFINE_bool("uncased", default=False,
help="Use uncased.")
flags.DEFINE_string("cls_scope", default=None,
help="Classifier layer scope.")
flags.DEFINE_bool("is_regression", default=False,
help="Whether it's a regression task.")
FLAGS = flags.FLAGS
SEG_ID_A = 0
SEG_ID_B = 1
SEG_ID_CLS = 2
SEG_ID_SEP = 3
SEG_ID_PAD = 4
class PaddingInputExample(object):
"""Fake example so the num input examples is a multiple of the batch size.
When running eval/predict on the TPU, we need to pad the number of examples
to be a multiple of the batch size, because the TPU requires a fixed batch
size. The alternative is to drop the last batch, which is bad because it means
the entire output data won't be generated.
We use this class instead of `None` because treating `None` as padding
battches could cause silent errors.
"""
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
input_ids,
input_mask,
segment_ids,
label_id,
is_real_example=True):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
self.is_real_example = is_real_example
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def convert_single_example(ex_index, example, label_list, max_seq_length,
tokenize_fn):
"""Converts a single `InputExample` into a single `InputFeatures`."""
if isinstance(example, PaddingInputExample):
return InputFeatures(
input_ids=[0] * max_seq_length,
input_mask=[1] * max_seq_length,
segment_ids=[0] * max_seq_length,
label_id=0,
is_real_example=False)
if label_list is not None:
label_map = {}
for (i, label) in enumerate(label_list):
label_map[label] = i
tokens_a = tokenize_fn(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenize_fn(example.text_b)
if tokens_b:
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for two [SEP] & one [CLS] with "- 3"
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
else:
# Account for one [SEP] & one [CLS] with "- 2"
if len(tokens_a) > max_seq_length - 2:
tokens_a = tokens_a[:max_seq_length - 2]
tokens = []
segment_ids = []
for token in tokens_a:
tokens.append(token)
segment_ids.append(SEG_ID_A)
tokens.append(SEP_ID)
segment_ids.append(SEG_ID_A)
if tokens_b:
for token in tokens_b:
tokens.append(token)
segment_ids.append(SEG_ID_B)
tokens.append(SEP_ID)
segment_ids.append(SEG_ID_B)
tokens.append(CLS_ID)
segment_ids.append(SEG_ID_CLS)
input_ids = tokens
# The mask has 0 for real tokens and 1 for padding tokens. Only real
# tokens are attended to.
input_mask = [0] * len(input_ids)
# Zero-pad up to the sequence length.
if len(input_ids) < max_seq_length:
delta_len = max_seq_length - len(input_ids)
input_ids = [0] * delta_len + input_ids
input_mask = [1] * delta_len + input_mask
segment_ids = [SEG_ID_PAD] * delta_len + segment_ids
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
if label_list is not None:
label_id = label_map[example.label]
else:
label_id = example.label
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label: {} (id = {})".format(example.label, label_id))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id)
return feature
def convert_single_example_for_inews(ex_index, tokens_a, tokens_b, label_map, max_seq_length,
tokenizer, example):
if tokens_b:
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for two [SEP] & one [CLS] with "- 3"
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
else:
# Account for one [SEP] & one [CLS] with "- 2"
if len(tokens_a) > max_seq_length - 2:
tokens_a = tokens_a[:max_seq_length - 2]
tokens = []
segment_ids = []
for token in tokens_a:
tokens.append(token)
segment_ids.append(SEG_ID_A)
tokens.append(SEP_ID)
segment_ids.append(SEG_ID_A)
if tokens_b:
for token in tokens_b:
tokens.append(token)
segment_ids.append(SEG_ID_B)
tokens.append(SEP_ID)
segment_ids.append(SEG_ID_B)
tokens.append(CLS_ID)
segment_ids.append(SEG_ID_CLS)
input_ids = tokens
# The mask has 0 for real tokens and 1 for padding tokens. Only real
# tokens are attended to.
input_mask = [0] * len(input_ids)
# Zero-pad up to the sequence length.
if len(input_ids) < max_seq_length:
delta_len = max_seq_length - len(input_ids)
input_ids = [0] * delta_len + input_ids
input_mask = [1] * delta_len + input_mask
segment_ids = [SEG_ID_PAD] * delta_len + segment_ids
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
if label_map is not None:
label_id = label_map[example.label]
else:
label_id = example.label
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label: {} (id = {})".format(example.label, label_id))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id)
return feature
def convert_example_list_for_inews(ex_index, example, label_list, max_seq_length,
tokenizer):
"""Converts a single `InputExample` into a single `InputFeatures`."""
if isinstance(example, PaddingInputExample):
return [InputFeatures(
input_ids=[0] * max_seq_length,
input_mask=[0] * max_seq_length,
segment_ids=[0] * max_seq_length,
label_id=0,
is_real_example=False)]
label_map = {}
for (i, label) in enumerate(label_list):
label_map[label] = i
tokens_a = tokenizer(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer(example.text_b)
must_len = len(tokens_a) + 3
extra_len = max_seq_length - must_len
feature_list = []
if example.text_b and extra_len > 0:
extra_num = int((len(tokens_b) - 1) / extra_len) + 1
for num in range(extra_num):
max_len = min((num + 1) * extra_len, len(tokens_b))
tokens_b_sub = tokens_b[num * extra_len: max_len]
feature = convert_single_example_for_inews(
ex_index, tokens_a, tokens_b_sub, label_map, max_seq_length, tokenizer, example)
feature_list.append(feature)
else:
feature = convert_single_example_for_inews(
ex_index, tokens_a, tokens_b, label_map, max_seq_length, tokenizer, example)
feature_list.append(feature)
return feature_list
def file_based_convert_examples_to_features_for_inews(
examples, label_list, max_seq_length, tokenizer, output_file, num_passes=1):
"""Convert a set of `InputExample`s to a TFRecord file."""
writer = tf.python_io.TFRecordWriter(output_file)
num_example = 0
if num_passes > 1:
examples *= num_passes
for (ex_index, example) in enumerate(examples):
if ex_index % 1000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature_list = convert_example_list_for_inews(ex_index, example, label_list,
max_seq_length, tokenizer)
num_example += len(feature_list)
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
features = collections.OrderedDict()
for feature in feature_list:
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["label_ids"] = create_int_feature([feature.label_id])
features["is_real_example"] = create_int_feature(
[int(feature.is_real_example)])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
tf.logging.info("feature num: %s", num_example)
writer.close()
def file_based_convert_examples_to_features(
examples, label_list, max_seq_length, tokenize_fn, output_file,
num_passes=1):
"""Convert a set of `InputExample`s to a TFRecord file."""
print(len(examples))
sys.stdout.flush()
# do not create duplicated records
if tf.gfile.Exists(output_file) and not FLAGS.overwrite_data:
tf.logging.info("Do not overwrite tfrecord {} exists.".format(output_file))
return
tf.logging.info("Create new tfrecord {}.".format(output_file))
writer = tf.python_io.TFRecordWriter(output_file)
if num_passes > 1:
examples *= num_passes
print(len(examples))
sys.stdout.flush()
for (ex_index, example) in enumerate(examples):
if ex_index % 10000 == 0:
tf.logging.info("Writing example {} of {}".format(ex_index,
len(examples)))
feature = convert_single_example(ex_index, example, label_list,
max_seq_length, tokenize_fn)
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
def create_float_feature(values):
f = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
return f
features = collections.OrderedDict()
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_float_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
if label_list is not None:
features["label_ids"] = create_int_feature([feature.label_id])
else:
features["label_ids"] = create_float_feature([float(feature.label_id)])
features["is_real_example"] = create_int_feature(
[int(feature.is_real_example)])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
writer.close()
def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.float32),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([], tf.int64),
"is_real_example": tf.FixedLenFeature([], tf.int64),
}
if FLAGS.is_regression:
name_to_features["label_ids"] = tf.FixedLenFeature([], tf.float32)
tf.logging.info("Input tfrecord file {}".format(input_file))
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.cast(t, tf.int32)
example[name] = t
return example
def input_fn(params, input_context=None):
"""The actual input function."""
if FLAGS.use_tpu:
batch_size = params["batch_size"]
elif is_training:
batch_size = FLAGS.train_batch_size
elif FLAGS.do_eval:
batch_size = FLAGS.eval_batch_size
else:
batch_size = FLAGS.predict_batch_size
d = tf.data.TFRecordDataset(input_file)
# Shard the dataset to difference devices
if input_context is not None:
tf.logging.info("Input pipeline id %d out of %d",
input_context.input_pipeline_id, input_context.num_replicas_in_sync)
d = d.shard(input_context.num_input_pipelines,
input_context.input_pipeline_id)
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
if is_training:
d = d.shuffle(buffer_size=FLAGS.shuffle_buffer)
d = d.repeat()
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder))
return d
return input_fn
def get_model_fn(n_class):
def model_fn(features, labels, mode, params):
#### Training or Evaluation
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
# Get loss from inputs
if FLAGS.is_regression:
(total_loss, per_example_loss, logits
) = function_builder.get_regression_loss(FLAGS, features, is_training)
else:
(total_loss, per_example_loss, logits
) = function_builder.get_classification_loss(
FLAGS, features, n_class, is_training)
# Check model parameters
num_params = sum([np.prod(v.shape) for v in tf.trainable_variables()])
tf.logging.info('#params: {}'.format(num_params))
# load pretrained models
scaffold_fn = model_utils.init_from_checkpoint(FLAGS)
# Evaluation mode
if mode == tf.estimator.ModeKeys.EVAL:
assert FLAGS.num_hosts == 1
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
eval_input_dict = {
'labels': label_ids,
'predictions': predictions,
'weights': is_real_example
}
accuracy = tf.metrics.accuracy(**eval_input_dict)
loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
return {
'eval_accuracy': accuracy,
'eval_loss': loss}
def regression_metric_fn(
per_example_loss, label_ids, logits, is_real_example):
loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
pearsonr = tf.contrib.metrics.streaming_pearson_correlation(
logits, label_ids, weights=is_real_example)
return {'eval_loss': loss, 'eval_pearsonr': pearsonr}
is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32)
# Constucting evaluation TPUEstimatorSpec with new cache.
label_ids = tf.reshape(features['label_ids'], [-1])
if FLAGS.is_regression:
metric_fn = regression_metric_fn
else:
metric_fn = metric_fn
metric_args = [per_example_loss, label_ids, logits, is_real_example]
if FLAGS.use_tpu:
eval_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=(metric_fn, metric_args),
scaffold_fn=scaffold_fn)
else:
eval_spec = tf.estimator.EstimatorSpec(
mode=mode,
loss=total_loss,
eval_metric_ops=metric_fn(*metric_args))
return eval_spec
elif mode == tf.estimator.ModeKeys.PREDICT:
label_ids = tf.reshape(features["label_ids"], [-1])
predictions = {
"logits": logits,
"labels": label_ids,
"is_real": features["is_real_example"]
}
if FLAGS.use_tpu:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
else:
output_spec = tf.estimator.EstimatorSpec(
mode=mode, predictions=predictions)
return output_spec
# Configuring the optimizer
train_op, learning_rate, _ = model_utils.get_train_op(FLAGS, total_loss)
monitor_dict = {}
monitor_dict["lr"] = learning_rate
# Constucting training TPUEstimatorSpec with new cache.
if FLAGS.use_tpu:
# Creating host calls
if not FLAGS.is_regression:
label_ids = tf.reshape(features['label_ids'], [-1])
predictions = tf.argmax(logits, axis=-1, output_type=label_ids.dtype)
is_correct = tf.equal(predictions, label_ids)
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))
monitor_dict["accuracy"] = accuracy
host_call = function_builder.construct_scalar_host_call(
monitor_dict=monitor_dict,
model_dir=FLAGS.model_dir,
prefix="train/",
reduce_fn=tf.reduce_mean)
else:
host_call = None
train_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, loss=total_loss, train_op=train_op, host_call=host_call,
scaffold_fn=scaffold_fn)
else:
train_spec = tf.estimator.EstimatorSpec(
mode=mode, loss=total_loss, train_op=train_op)
return train_spec
return model_fn
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
# Validate flags
if FLAGS.save_steps is not None:
FLAGS.iterations = min(FLAGS.iterations, FLAGS.save_steps)
if FLAGS.do_predict:
predict_dir = FLAGS.predict_dir
if not tf.gfile.Exists(predict_dir):
tf.gfile.MakeDirs(predict_dir)
processors = {
"xnli": XnliProcessor,
"tnews": TnewsProcessor,
"afqmc": AFQMCProcessor,
"iflytek": iFLYTEKDataProcessor,
"copa": COPAProcessor,
"cmnli": CMNLIProcessor,
"wsc": WSCProcessor,
"csl": CslProcessor,
"copa": COPAProcessor,
}
if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:
raise ValueError(
"At least one of `do_train`, `do_eval, `do_predict` or "
"`do_submit` must be True.")
if not tf.gfile.Exists(FLAGS.output_dir):
tf.gfile.MakeDirs(FLAGS.output_dir)
task_name = FLAGS.task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
label_list = processor.get_labels() if not FLAGS.is_regression else None
sp = spm.SentencePieceProcessor()
sp.Load(FLAGS.spiece_model_file)
def tokenize_fn(text):
text = preprocess_text(text, lower=FLAGS.uncased)
return encode_ids(sp, text)
run_config = model_utils.configure_tpu(FLAGS)
model_fn = get_model_fn(len(label_list) if label_list is not None else None)
spm_basename = os.path.basename(FLAGS.spiece_model_file)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
if FLAGS.use_tpu:
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
predict_batch_size=FLAGS.predict_batch_size,
eval_batch_size=FLAGS.eval_batch_size)
else:
estimator = tf.estimator.Estimator(
model_fn=model_fn,
config=run_config)
if FLAGS.do_train:
train_file_base = "{}.len-{}.train.tf_record".format(
spm_basename, FLAGS.max_seq_length)
train_file = os.path.join(FLAGS.output_dir, train_file_base)
tf.logging.info("Use tfrecord file {}".format(train_file))
train_examples = processor.get_train_examples(FLAGS.data_dir)
np.random.shuffle(train_examples)
tf.logging.info("Num of train samples: {}".format(len(train_examples)))
if task_name == "inews":
file_based_convert_examples_to_features_for_inews(
train_examples, label_list, FLAGS.max_seq_length, tokenize_fn,
train_file, FLAGS.num_passes)
else:
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenize_fn,
train_file, FLAGS.num_passes)
# here we use epoch number to calculate total train_steps
train_steps = int(len(train_examples) * FLAGS.num_train_epochs / FLAGS.train_batch_size)
FLAGS.warmup_steps = int(0.1 * train_steps)
train_input_fn = file_based_input_fn_builder(
input_file=train_file,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=train_steps)
if FLAGS.do_eval or FLAGS.do_predict:
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
tf.logging.info("Num of eval samples: {}".format(len(eval_examples)))
if FLAGS.do_eval:
# TPU requires a fixed batch size for all batches, therefore the number
# of examples must be a multiple of the batch size, or else examples
# will get dropped. So we pad with fake examples which are ignored
# later on. These do NOT count towards the metric (all tf.metrics
# support a per-instance weight, and these get a weight of 0.0).
#
# Modified in XL: We also adopt the same mechanism for GPUs.
while len(eval_examples) % FLAGS.eval_batch_size != 0:
eval_examples.append(PaddingInputExample())
eval_file_base = "{}.len-{}.{}.eval.tf_record".format(
spm_basename, FLAGS.max_seq_length, FLAGS.eval_split)
eval_file = os.path.join(FLAGS.output_dir, eval_file_base)
if task_name == "inews":
file_based_convert_examples_to_features_for_inews(
eval_examples, label_list, FLAGS.max_seq_length, tokenize_fn,
eval_file)
else:
file_based_convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenize_fn,
eval_file)
assert len(eval_examples) % FLAGS.eval_batch_size == 0
eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)
eval_input_fn = file_based_input_fn_builder(
input_file=eval_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=True)
# Filter out all checkpoints in the directory
steps_and_files = []
filenames = tf.gfile.ListDirectory(FLAGS.model_dir)
for filename in filenames:
if filename.endswith(".index"):
ckpt_name = filename[:-6]
cur_filename = join(FLAGS.model_dir, ckpt_name)
global_step = int(cur_filename.split("-")[-1])
tf.logging.info("Add {} to eval list.".format(cur_filename))
steps_and_files.append([global_step, cur_filename])
steps_and_files = sorted(steps_and_files, key=lambda x: x[0])
# Decide whether to evaluate all ckpts
if not FLAGS.eval_all_ckpt:
steps_and_files = steps_and_files[-1:]
eval_results = []
output_eval_file = os.path.join(FLAGS.data_dir, "dev_results_bert.txt")
print("output_eval_file:", output_eval_file)
tf.logging.info("output_eval_file:" + output_eval_file)
with tf.gfile.GFile(output_eval_file, "w") as writer:
for global_step, filename in sorted(steps_and_files, key=lambda x: x[0]):
ret = estimator.evaluate(
input_fn=eval_input_fn,
steps=eval_steps,
checkpoint_path=filename)
ret["step"] = global_step
ret["path"] = filename
eval_results.append(ret)
tf.logging.info("=" * 80)
log_str = "Eval result | "
for key, val in sorted(ret.items(), key=lambda x: x[0]):
log_str += "{} {} | ".format(key, val)
writer.write("%s = %s\n" % (key, val))
tf.logging.info(log_str)
key_name = "eval_pearsonr" if FLAGS.is_regression else "eval_accuracy"
eval_results.sort(key=lambda x: x[key_name], reverse=True)
tf.logging.info("=" * 80)
log_str = "Best result | "
for key, val in sorted(eval_results[0].items(), key=lambda x: x[0]):
log_str += "{} {} | ".format(key, val)
tf.logging.info(log_str)
if FLAGS.do_predict:
eval_examples = processor.get_test_examples(FLAGS.data_dir)
eval_file_base = "{}.len-{}.{}.predict.tf_record".format(
spm_basename, FLAGS.max_seq_length, FLAGS.eval_split)
eval_file = os.path.join(FLAGS.output_dir, eval_file_base)
if task_name == "inews":
file_based_convert_examples_to_features_for_inews(
eval_examples, label_list, FLAGS.max_seq_length, tokenize_fn,
eval_file)
else:
file_based_convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenize_fn,
eval_file)
pred_input_fn = file_based_input_fn_builder(
input_file=eval_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=False)
result = estimator.predict(input_fn=predict_input_fn)
index2label_map = {}
for (i, label) in enumerate(label_list):
index2label_map[i] = label
output_predict_file_label_name = task_name + "_predict.json"
output_predict_file_label = os.path.join(FLAGS.output_dir, output_predict_file_label_name)
output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
with tf.gfile.GFile(output_predict_file_label, "w") as writer_label:
with tf.gfile.GFile(output_predict_file, "w") as writer:
num_written_lines = 0
tf.logging.info("***** Predict results *****")
for (i, prediction) in enumerate(result):
probabilities = prediction["probabilities"]
label_index = probabilities.argmax(0)
if i >= num_actual_predict_examples:
break
output_line = "\t".join(
str(class_probability)
for class_probability in probabilities) + "\n"
test_label_dict = {}
test_label_dict["id"] = i
test_label_dict["label"] = str(index2label_map[label_index])
if task_name == "tnews":
test_label_dict["label_desc"] = ""
writer.write(output_line)
json.dump(test_label_dict, writer_label)
writer_label.write("\n")
num_written_lines += 1
assert num_written_lines == num_actual_predict_examples
output_predict_file_label_name = task_name + "_predict.json"
output_predict_file_label = os.path.join(FLAGS.output_dir, output_predict_file_label_name)
predict_results = []
with tf.gfile.GFile(output_predict_file_label, "w") as writer_label:
with tf.gfile.Open(os.path.join(predict_dir, "{}.tsv".format(
task_name)), "w") as fout:
fout.write("index\tprediction\n")
for pred_cnt, result in enumerate(estimator.predict(
input_fn=pred_input_fn,
yield_single_examples=True,
checkpoint_path=FLAGS.predict_ckpt)):
if pred_cnt % 1000 == 0:
tf.logging.info("Predicting submission for example: {}".format(
pred_cnt))
logits = [float(x) for x in result["logits"].flat]
predict_results.append(logits)
if len(logits) == 1:
label_out = logits[0]
elif len(logits) == 2:
if logits[1] - logits[0] > FLAGS.predict_threshold:
label_out = label_list[1]
else:
label_out = label_list[0]
elif len(logits) > 2:
max_index = np.argmax(np.array(logits, dtype=np.float32))
label_out = label_list[max_index]
else:
raise NotImplementedError
fout.write("{}\t{}\n".format(pred_cnt, label_out))
test_label_dict = {}
test_label_dict["id"] = pred_cnt
test_label_dict["label"] = str(label_out)
if task_name == "tnews":
test_label_dict["label_desc"] = ""
writer.write(output_line)
json.dump(test_label_dict, writer_label)
writer_label.write("\n")
predict_json_path = os.path.join(predict_dir, "{}.logits.json".format(
task_name))
with tf.gfile.Open(predict_json_path, "w") as fp:
json.dump(predict_results, fp, indent=4)
if __name__ == "__main__":
tf.app.run()
| 35,361 | 35.912317 | 94 | py |
CLUE | CLUE-master/baselines/models/xlnet/squad_utils.py | """Official evaluation script for SQuAD version 2.0.
In addition to basic functionality, we also compute additional statistics and
plot precision-recall curves if an additional na_prob.json file is provided.
This file is expected to map question ID's to the model's predicted probability
that a question is unanswerable.
"""
import argparse
import collections
import json
import numpy as np
import os
import re
import string
import sys
OPTS = None
def parse_args():
parser = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.')
parser.add_argument('data_file', metavar='data.json', help='Input data JSON file.')
parser.add_argument('pred_file', metavar='pred.json', help='Model predictions.')
parser.add_argument('--out-file', '-o', metavar='eval.json',
help='Write accuracy metrics to file (default is stdout).')
parser.add_argument('--na-prob-file', '-n', metavar='na_prob.json',
help='Model estimates of probability of no answer.')
parser.add_argument('--na-prob-thresh', '-t', type=float, default=1.0,
help='Predict "" if no-answer probability exceeds this (default = 1.0).')
parser.add_argument('--out-image-dir', '-p', metavar='out_images', default=None,
help='Save precision-recall curves to directory.')
parser.add_argument('--verbose', '-v', action='store_true')
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
return parser.parse_args()
def make_qid_to_has_ans(dataset):
qid_to_has_ans = {}
for article in dataset:
for p in article['paragraphs']:
for qa in p['qas']:
qid_to_has_ans[qa['id']] = bool(qa['answers'])
return qid_to_has_ans
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
regex = re.compile(r'\b(a|an|the)\b', re.UNICODE)
return re.sub(regex, ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def get_tokens(s):
if not s: return []
return normalize_answer(s).split()
def compute_exact(a_gold, a_pred):
return int(normalize_answer(a_gold) == normalize_answer(a_pred))
def compute_f1(a_gold, a_pred):
gold_toks = get_tokens(a_gold)
pred_toks = get_tokens(a_pred)
common = collections.Counter(gold_toks) & collections.Counter(pred_toks)
num_same = sum(common.values())
if len(gold_toks) == 0 or len(pred_toks) == 0:
# If either is no-answer, then F1 is 1 if they agree, 0 otherwise
return int(gold_toks == pred_toks)
if num_same == 0:
return 0
precision = 1.0 * num_same / len(pred_toks)
recall = 1.0 * num_same / len(gold_toks)
f1 = (2 * precision * recall) / (precision + recall)
return f1
def get_raw_scores(dataset, preds):
exact_scores = {}
f1_scores = {}
for article in dataset:
for p in article['paragraphs']:
for qa in p['qas']:
qid = qa['id']
gold_answers = [a['text'] for a in qa['answers']
if normalize_answer(a['text'])]
if not gold_answers:
# For unanswerable questions, only correct answer is empty string
gold_answers = ['']
if qid not in preds:
print('Missing prediction for %s' % qid)
continue
a_pred = preds[qid]
# Take max over all gold answers
exact_scores[qid] = max(compute_exact(a, a_pred) for a in gold_answers)
f1_scores[qid] = max(compute_f1(a, a_pred) for a in gold_answers)
return exact_scores, f1_scores
def apply_no_ans_threshold(scores, na_probs, qid_to_has_ans, na_prob_thresh):
new_scores = {}
for qid, s in scores.items():
pred_na = na_probs[qid] > na_prob_thresh
if pred_na:
new_scores[qid] = float(not qid_to_has_ans[qid])
else:
new_scores[qid] = s
return new_scores
def make_eval_dict(exact_scores, f1_scores, qid_list=None):
if not qid_list:
total = len(exact_scores)
return collections.OrderedDict([
('exact', 100.0 * sum(exact_scores.values()) / total),
('f1', 100.0 * sum(f1_scores.values()) / total),
('total', total),
])
else:
total = len(qid_list)
return collections.OrderedDict([
('exact', 100.0 * sum(exact_scores[k] for k in qid_list) / total),
('f1', 100.0 * sum(f1_scores[k] for k in qid_list) / total),
('total', total),
])
def merge_eval(main_eval, new_eval, prefix):
for k in new_eval:
main_eval['%s_%s' % (prefix, k)] = new_eval[k]
def plot_pr_curve(precisions, recalls, out_image, title):
plt.step(recalls, precisions, color='b', alpha=0.2, where='post')
plt.fill_between(recalls, precisions, step='post', alpha=0.2, color='b')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.xlim([0.0, 1.05])
plt.ylim([0.0, 1.05])
plt.title(title)
plt.savefig(out_image)
plt.clf()
def make_precision_recall_eval(scores, na_probs, num_true_pos, qid_to_has_ans,
out_image=None, title=None):
qid_list = sorted(na_probs, key=lambda k: na_probs[k])
true_pos = 0.0
cur_p = 1.0
cur_r = 0.0
precisions = [1.0]
recalls = [0.0]
avg_prec = 0.0
for i, qid in enumerate(qid_list):
if qid_to_has_ans[qid]:
true_pos += scores[qid]
cur_p = true_pos / float(i+1)
cur_r = true_pos / float(num_true_pos)
if i == len(qid_list) - 1 or na_probs[qid] != na_probs[qid_list[i+1]]:
# i.e., if we can put a threshold after this point
avg_prec += cur_p * (cur_r - recalls[-1])
precisions.append(cur_p)
recalls.append(cur_r)
if out_image:
plot_pr_curve(precisions, recalls, out_image, title)
return {'ap': 100.0 * avg_prec}
def run_precision_recall_analysis(main_eval, exact_raw, f1_raw, na_probs,
qid_to_has_ans, out_image_dir):
if out_image_dir and not os.path.exists(out_image_dir):
os.makedirs(out_image_dir)
num_true_pos = sum(1 for v in qid_to_has_ans.values() if v)
if num_true_pos == 0:
return
pr_exact = make_precision_recall_eval(
exact_raw, na_probs, num_true_pos, qid_to_has_ans,
out_image=os.path.join(out_image_dir, 'pr_exact.png'),
title='Precision-Recall curve for Exact Match score')
pr_f1 = make_precision_recall_eval(
f1_raw, na_probs, num_true_pos, qid_to_has_ans,
out_image=os.path.join(out_image_dir, 'pr_f1.png'),
title='Precision-Recall curve for F1 score')
oracle_scores = {k: float(v) for k, v in qid_to_has_ans.items()}
pr_oracle = make_precision_recall_eval(
oracle_scores, na_probs, num_true_pos, qid_to_has_ans,
out_image=os.path.join(out_image_dir, 'pr_oracle.png'),
title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)')
merge_eval(main_eval, pr_exact, 'pr_exact')
merge_eval(main_eval, pr_f1, 'pr_f1')
merge_eval(main_eval, pr_oracle, 'pr_oracle')
def histogram_na_prob(na_probs, qid_list, image_dir, name):
if not qid_list:
return
x = [na_probs[k] for k in qid_list]
weights = np.ones_like(x) / float(len(x))
plt.hist(x, weights=weights, bins=20, range=(0.0, 1.0))
plt.xlabel('Model probability of no-answer')
plt.ylabel('Proportion of dataset')
plt.title('Histogram of no-answer probability: %s' % name)
plt.savefig(os.path.join(image_dir, 'na_prob_hist_%s.png' % name))
plt.clf()
def find_best_thresh(preds, scores, na_probs, qid_to_has_ans):
num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k])
cur_score = num_no_ans
best_score = cur_score
best_thresh = 0.0
qid_list = sorted(na_probs, key=lambda k: na_probs[k])
for i, qid in enumerate(qid_list):
if qid not in scores: continue
if qid_to_has_ans[qid]:
diff = scores[qid]
else:
if preds[qid]:
diff = -1
else:
diff = 0
cur_score += diff
if cur_score > best_score:
best_score = cur_score
best_thresh = na_probs[qid]
return 100.0 * best_score / len(scores), best_thresh
def find_best_thresh_v2(preds, scores, na_probs, qid_to_has_ans):
num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k])
cur_score = num_no_ans
best_score = cur_score
best_thresh = 0.0
qid_list = sorted(na_probs, key=lambda k: na_probs[k])
for i, qid in enumerate(qid_list):
if qid not in scores: continue
if qid_to_has_ans[qid]:
diff = scores[qid]
else:
if preds[qid]:
diff = -1
else:
diff = 0
cur_score += diff
if cur_score > best_score:
best_score = cur_score
best_thresh = na_probs[qid]
has_ans_score, has_ans_cnt = 0, 0
for qid in qid_list:
if not qid_to_has_ans[qid]: continue
has_ans_cnt += 1
if qid not in scores: continue
has_ans_score += scores[qid]
return 100.0 * best_score / len(scores), best_thresh, 1.0 * has_ans_score / has_ans_cnt
def find_all_best_thresh(main_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans):
best_exact, exact_thresh = find_best_thresh(preds, exact_raw, na_probs, qid_to_has_ans)
best_f1, f1_thresh = find_best_thresh(preds, f1_raw, na_probs, qid_to_has_ans)
main_eval['best_exact'] = best_exact
main_eval['best_exact_thresh'] = exact_thresh
main_eval['best_f1'] = best_f1
main_eval['best_f1_thresh'] = f1_thresh
def find_all_best_thresh_v2(main_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans):
best_exact, exact_thresh, has_ans_exact = find_best_thresh_v2(preds, exact_raw, na_probs, qid_to_has_ans)
best_f1, f1_thresh, has_ans_f1 = find_best_thresh_v2(preds, f1_raw, na_probs, qid_to_has_ans)
main_eval['best_exact'] = best_exact
main_eval['best_exact_thresh'] = exact_thresh
main_eval['best_f1'] = best_f1
main_eval['best_f1_thresh'] = f1_thresh
main_eval['has_ans_exact'] = has_ans_exact
main_eval['has_ans_f1'] = has_ans_f1
def main():
with open(OPTS.data_file) as f:
dataset_json = json.load(f)
dataset = dataset_json['data']
with open(OPTS.pred_file) as f:
preds = json.load(f)
new_orig_data = []
for article in dataset:
for p in article['paragraphs']:
for qa in p['qas']:
if qa['id'] in preds:
new_para = {'qas': [qa]}
new_article = {'paragraphs': [new_para]}
new_orig_data.append(new_article)
dataset = new_orig_data
if OPTS.na_prob_file:
with open(OPTS.na_prob_file) as f:
na_probs = json.load(f)
else:
na_probs = {k: 0.0 for k in preds}
qid_to_has_ans = make_qid_to_has_ans(dataset) # maps qid to True/False
has_ans_qids = [k for k, v in qid_to_has_ans.items() if v]
no_ans_qids = [k for k, v in qid_to_has_ans.items() if not v]
exact_raw, f1_raw = get_raw_scores(dataset, preds)
exact_thresh = apply_no_ans_threshold(exact_raw, na_probs, qid_to_has_ans,
OPTS.na_prob_thresh)
f1_thresh = apply_no_ans_threshold(f1_raw, na_probs, qid_to_has_ans,
OPTS.na_prob_thresh)
out_eval = make_eval_dict(exact_thresh, f1_thresh)
if has_ans_qids:
has_ans_eval = make_eval_dict(exact_thresh, f1_thresh, qid_list=has_ans_qids)
merge_eval(out_eval, has_ans_eval, 'HasAns')
if no_ans_qids:
no_ans_eval = make_eval_dict(exact_thresh, f1_thresh, qid_list=no_ans_qids)
merge_eval(out_eval, no_ans_eval, 'NoAns')
if OPTS.na_prob_file:
find_all_best_thresh(out_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans)
if OPTS.na_prob_file and OPTS.out_image_dir:
run_precision_recall_analysis(out_eval, exact_raw, f1_raw, na_probs,
qid_to_has_ans, OPTS.out_image_dir)
histogram_na_prob(na_probs, has_ans_qids, OPTS.out_image_dir, 'hasAns')
histogram_na_prob(na_probs, no_ans_qids, OPTS.out_image_dir, 'noAns')
if OPTS.out_file:
with open(OPTS.out_file, 'w') as f:
json.dump(out_eval, f)
else:
print(json.dumps(out_eval, indent=2))
if __name__ == '__main__':
OPTS = parse_args()
if OPTS.out_image_dir:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
main()
| 12,252 | 36.356707 | 107 | py |
CLUE | CLUE-master/baselines/models/xlnet/function_builder.py | """doc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import os
import tensorflow as tf
import modeling
import xlnet
def construct_scalar_host_call(
monitor_dict,
model_dir,
prefix="",
reduce_fn=None):
"""
Construct host calls to monitor training progress on TPUs.
"""
metric_names = list(monitor_dict.keys())
def host_call_fn(global_step, *args):
"""actual host call function."""
step = global_step[0]
with tf.contrib.summary.create_file_writer(
logdir=model_dir, filename_suffix=".host_call").as_default():
with tf.contrib.summary.always_record_summaries():
for i, name in enumerate(metric_names):
if reduce_fn is None:
scalar = args[i][0]
else:
scalar = reduce_fn(args[i])
with tf.contrib.summary.record_summaries_every_n_global_steps(
100, global_step=step):
tf.contrib.summary.scalar(prefix + name, scalar, step=step)
return tf.contrib.summary.all_summary_ops()
global_step_tensor = tf.reshape(tf.train.get_or_create_global_step(), [1])
other_tensors = [tf.reshape(monitor_dict[key], [1]) for key in metric_names]
return host_call_fn, [global_step_tensor] + other_tensors
def two_stream_loss(FLAGS, features, labels, mems, is_training):
"""Pretraining loss with two-stream attention Transformer-XL."""
#### Unpack input
mem_name = "mems"
mems = mems.get(mem_name, None)
inp_k = tf.transpose(features["input_k"], [1, 0])
inp_q = tf.transpose(features["input_q"], [1, 0])
seg_id = tf.transpose(features["seg_id"], [1, 0])
inp_mask = None
perm_mask = tf.transpose(features["perm_mask"], [1, 2, 0])
if FLAGS.num_predict is not None:
# [num_predict x tgt_len x bsz]
target_mapping = tf.transpose(features["target_mapping"], [1, 2, 0])
else:
target_mapping = None
# target for LM loss
tgt = tf.transpose(features["target"], [1, 0])
# target mask for LM loss
tgt_mask = tf.transpose(features["target_mask"], [1, 0])
# construct xlnet config and save to model_dir
xlnet_config = xlnet.XLNetConfig(FLAGS=FLAGS)
xlnet_config.to_json(os.path.join(FLAGS.model_dir, "config.json"))
# construct run config from FLAGS
run_config = xlnet.create_run_config(is_training, False, FLAGS)
xlnet_model = xlnet.XLNetModel(
xlnet_config=xlnet_config,
run_config=run_config,
input_ids=inp_k,
seg_ids=seg_id,
input_mask=inp_mask,
mems=mems,
perm_mask=perm_mask,
target_mapping=target_mapping,
inp_q=inp_q)
output = xlnet_model.get_sequence_output()
new_mems = {mem_name: xlnet_model.get_new_memory()}
lookup_table = xlnet_model.get_embedding_table()
initializer = xlnet_model.get_initializer()
with tf.variable_scope("model", reuse=tf.AUTO_REUSE):
# LM loss
lm_loss = modeling.lm_loss(
hidden=output,
target=tgt,
n_token=xlnet_config.n_token,
d_model=xlnet_config.d_model,
initializer=initializer,
lookup_table=lookup_table,
tie_weight=True,
bi_data=run_config.bi_data,
use_tpu=run_config.use_tpu)
#### Quantity to monitor
monitor_dict = {}
if FLAGS.use_bfloat16:
tgt_mask = tf.cast(tgt_mask, tf.float32)
lm_loss = tf.cast(lm_loss, tf.float32)
total_loss = tf.reduce_sum(lm_loss * tgt_mask) / tf.reduce_sum(tgt_mask)
monitor_dict["total_loss"] = total_loss
return total_loss, new_mems, monitor_dict
def get_loss(FLAGS, features, labels, mems, is_training):
"""Pretraining loss with two-stream attention Transformer-XL."""
if FLAGS.use_bfloat16:
with tf.tpu.bfloat16_scope():
return two_stream_loss(FLAGS, features, labels, mems, is_training)
else:
return two_stream_loss(FLAGS, features, labels, mems, is_training)
def get_classification_loss(
FLAGS, features, n_class, is_training):
"""Loss for downstream classification tasks."""
bsz_per_core = tf.shape(features["input_ids"])[0]
inp = tf.transpose(features["input_ids"], [1, 0])
seg_id = tf.transpose(features["segment_ids"], [1, 0])
inp_mask = tf.transpose(features["input_mask"], [1, 0])
label = tf.reshape(features["label_ids"], [bsz_per_core])
xlnet_config = xlnet.XLNetConfig(json_path=FLAGS.model_config_path)
run_config = xlnet.create_run_config(is_training, True, FLAGS)
xlnet_model = xlnet.XLNetModel(
xlnet_config=xlnet_config,
run_config=run_config,
input_ids=inp,
seg_ids=seg_id,
input_mask=inp_mask)
summary = xlnet_model.get_pooled_out(FLAGS.summary_type, FLAGS.use_summ_proj)
with tf.variable_scope("model", reuse=tf.AUTO_REUSE):
if FLAGS.cls_scope is not None and FLAGS.cls_scope:
cls_scope = "classification_{}".format(FLAGS.cls_scope)
else:
cls_scope = "classification_{}".format(FLAGS.task_name.lower())
per_example_loss, logits = modeling.classification_loss(
hidden=summary,
labels=label,
n_class=n_class,
initializer=xlnet_model.get_initializer(),
scope=cls_scope,
return_logits=True)
total_loss = tf.reduce_mean(per_example_loss)
return total_loss, per_example_loss, logits
def get_regression_loss(
FLAGS, features, is_training):
"""Loss for downstream regression tasks."""
bsz_per_core = tf.shape(features["input_ids"])[0]
inp = tf.transpose(features["input_ids"], [1, 0])
seg_id = tf.transpose(features["segment_ids"], [1, 0])
inp_mask = tf.transpose(features["input_mask"], [1, 0])
label = tf.reshape(features["label_ids"], [bsz_per_core])
xlnet_config = xlnet.XLNetConfig(json_path=FLAGS.model_config_path)
run_config = xlnet.create_run_config(is_training, True, FLAGS)
xlnet_model = xlnet.XLNetModel(
xlnet_config=xlnet_config,
run_config=run_config,
input_ids=inp,
seg_ids=seg_id,
input_mask=inp_mask)
summary = xlnet_model.get_pooled_out(FLAGS.summary_type, FLAGS.use_summ_proj)
with tf.variable_scope("model", reuse=tf.AUTO_REUSE):
per_example_loss, logits = modeling.regression_loss(
hidden=summary,
labels=label,
initializer=xlnet_model.get_initializer(),
scope="regression_{}".format(FLAGS.task_name.lower()),
return_logits=True)
total_loss = tf.reduce_mean(per_example_loss)
return total_loss, per_example_loss, logits
def get_qa_outputs(FLAGS, features, is_training):
"""Loss for downstream span-extraction QA tasks such as SQuAD."""
inp = tf.transpose(features["input_ids"], [1, 0])
seg_id = tf.transpose(features["segment_ids"], [1, 0])
inp_mask = tf.transpose(features["input_mask"], [1, 0])
seq_len = tf.shape(inp)[0]
xlnet_config = xlnet.XLNetConfig(json_path=FLAGS.model_config_path)
run_config = xlnet.create_run_config(is_training, True, FLAGS)
xlnet_model = xlnet.XLNetModel(
xlnet_config=xlnet_config,
run_config=run_config,
input_ids=inp,
seg_ids=seg_id,
input_mask=inp_mask)
output = xlnet_model.get_sequence_output()
initializer = xlnet_model.get_initializer()
return_dict = {}
# invalid position mask such as query and special symbols (PAD, SEP, CLS)
p_mask = features["p_mask"]
# logit of the start position
with tf.variable_scope("start_logits"):
start_logits = tf.layers.dense(
output,
1,
kernel_initializer=initializer)
start_logits = tf.transpose(tf.squeeze(start_logits, -1), [1, 0])
start_logits_masked = start_logits * (1 - p_mask) - 1e30 * p_mask
start_log_probs = tf.nn.log_softmax(start_logits_masked, -1)
# logit of the end position
with tf.variable_scope("end_logits"):
if is_training:
# during training, compute the end logits based on the
# ground truth of the start position
start_positions = tf.reshape(features["start_positions"], [-1])
start_index = tf.one_hot(start_positions, depth=seq_len, axis=-1,
dtype=tf.float32)
start_features = tf.einsum("lbh,bl->bh", output, start_index)
start_features = tf.tile(start_features[None], [seq_len, 1, 1])
end_logits = tf.layers.dense(
tf.concat([output, start_features], axis=-1), xlnet_config.d_model,
kernel_initializer=initializer, activation=tf.tanh, name="dense_0")
end_logits = tf.contrib.layers.layer_norm(
end_logits, begin_norm_axis=-1)
end_logits = tf.layers.dense(
end_logits, 1,
kernel_initializer=initializer,
name="dense_1")
end_logits = tf.transpose(tf.squeeze(end_logits, -1), [1, 0])
end_logits_masked = end_logits * (1 - p_mask) - 1e30 * p_mask
end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)
else:
# during inference, compute the end logits based on beam search
start_top_log_probs, start_top_index = tf.nn.top_k(
start_log_probs, k=FLAGS.start_n_top)
start_index = tf.one_hot(start_top_index,
depth=seq_len, axis=-1, dtype=tf.float32)
start_features = tf.einsum("lbh,bkl->bkh", output, start_index)
end_input = tf.tile(output[:, :, None],
[1, 1, FLAGS.start_n_top, 1])
start_features = tf.tile(start_features[None],
[seq_len, 1, 1, 1])
end_input = tf.concat([end_input, start_features], axis=-1)
end_logits = tf.layers.dense(
end_input,
xlnet_config.d_model,
kernel_initializer=initializer,
activation=tf.tanh,
name="dense_0")
end_logits = tf.contrib.layers.layer_norm(end_logits,
begin_norm_axis=-1)
end_logits = tf.layers.dense(
end_logits,
1,
kernel_initializer=initializer,
name="dense_1")
end_logits = tf.reshape(end_logits, [seq_len, -1, FLAGS.start_n_top])
end_logits = tf.transpose(end_logits, [1, 2, 0])
end_logits_masked = end_logits * (
1 - p_mask[:, None]) - 1e30 * p_mask[:, None]
end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)
end_top_log_probs, end_top_index = tf.nn.top_k(
end_log_probs, k=FLAGS.end_n_top)
end_top_log_probs = tf.reshape(
end_top_log_probs,
[-1, FLAGS.start_n_top * FLAGS.end_n_top])
end_top_index = tf.reshape(
end_top_index,
[-1, FLAGS.start_n_top * FLAGS.end_n_top])
if is_training:
return_dict["start_log_probs"] = start_log_probs
return_dict["end_log_probs"] = end_log_probs
else:
return_dict["start_top_log_probs"] = start_top_log_probs
return_dict["start_top_index"] = start_top_index
return_dict["end_top_log_probs"] = end_top_log_probs
return_dict["end_top_index"] = end_top_index
return return_dict
def get_race_loss(FLAGS, features, is_training):
"""Loss for downstream multi-choice QA tasks such as RACE."""
bsz_per_core = tf.shape(features["input_ids"])[0]
def _transform_features(feature):
out = tf.reshape(feature, [bsz_per_core, 4, -1])
out = tf.transpose(out, [2, 0, 1])
out = tf.reshape(out, [-1, bsz_per_core * 4])
return out
inp = _transform_features(features["input_ids"])
seg_id = _transform_features(features["segment_ids"])
inp_mask = _transform_features(features["input_mask"])
label = tf.reshape(features["label_ids"], [bsz_per_core])
xlnet_config = xlnet.XLNetConfig(json_path=FLAGS.model_config_path)
run_config = xlnet.create_run_config(is_training, True, FLAGS)
xlnet_model = xlnet.XLNetModel(
xlnet_config=xlnet_config,
run_config=run_config,
input_ids=inp,
seg_ids=seg_id,
input_mask=inp_mask)
summary = xlnet_model.get_pooled_out(FLAGS.summary_type, FLAGS.use_summ_proj)
with tf.variable_scope("logits"):
logits = tf.layers.dense(summary, 1,
kernel_initializer=xlnet_model.get_initializer())
logits = tf.reshape(logits, [bsz_per_core, 4])
one_hot_target = tf.one_hot(label, 4)
per_example_loss = -tf.reduce_sum(
tf.nn.log_softmax(logits) * one_hot_target, -1)
total_loss = tf.reduce_mean(per_example_loss)
return total_loss, per_example_loss, logits
| 12,303 | 32.895317 | 79 | py |
CLUE | CLUE-master/baselines/models/xlnet/model_utils.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
import re
import numpy as np
import six
from os.path import join
from six.moves import zip
from absl import flags
import tensorflow as tf
def configure_tpu(FLAGS):
if FLAGS.use_tpu:
tpu_cluster = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
master = tpu_cluster.get_master()
else:
tpu_cluster = None
master = FLAGS.master
session_config = tf.ConfigProto(allow_soft_placement=True)
# Uncomment the following line if you hope to monitor GPU RAM growth
# session_config.gpu_options.allow_growth = True
if FLAGS.use_tpu:
strategy = None
tf.logging.info('Use TPU without distribute strategy.')
elif FLAGS.num_core_per_host == 1:
strategy = None
tf.logging.info('Single device mode.')
else:
strategy = tf.contrib.distribute.MirroredStrategy(
num_gpus=FLAGS.num_core_per_host)
tf.logging.info('Use MirroredStrategy with %d devices.',
strategy.num_replicas_in_sync)
per_host_input = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
master=master,
model_dir=FLAGS.model_dir,
session_config=session_config,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations,
num_shards=FLAGS.num_hosts * FLAGS.num_core_per_host,
per_host_input_for_training=per_host_input),
keep_checkpoint_max=FLAGS.max_save,
save_checkpoints_secs=None,
save_checkpoints_steps=FLAGS.save_steps,
train_distribute=strategy
)
return run_config
def init_from_checkpoint(FLAGS, global_vars=False):
tvars = tf.global_variables() if global_vars else tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if FLAGS.init_checkpoint is not None:
if FLAGS.init_checkpoint.endswith("latest"):
ckpt_dir = os.path.dirname(FLAGS.init_checkpoint)
init_checkpoint = tf.train.latest_checkpoint(ckpt_dir)
else:
init_checkpoint = FLAGS.init_checkpoint
tf.logging.info("Initialize from the ckpt {}".format(init_checkpoint))
(assignment_map, initialized_variable_names
) = get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if FLAGS.use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
# Log customized initialization
tf.logging.info("**** Global Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
return scaffold_fn
def get_train_op(FLAGS, total_loss, grads_and_vars=None):
global_step = tf.train.get_or_create_global_step()
# increase the learning rate linearly
if FLAGS.warmup_steps > 0:
warmup_lr = (tf.cast(global_step, tf.float32)
/ tf.cast(FLAGS.warmup_steps, tf.float32)
* FLAGS.learning_rate)
else:
warmup_lr = 0.0
# decay the learning rate
if FLAGS.decay_method == "poly":
decay_lr = tf.train.polynomial_decay(
FLAGS.learning_rate,
global_step=global_step - FLAGS.warmup_steps,
decay_steps=FLAGS.train_steps - FLAGS.warmup_steps,
end_learning_rate=FLAGS.learning_rate * FLAGS.min_lr_ratio)
elif FLAGS.decay_method == "cos":
decay_lr = tf.train.cosine_decay(
FLAGS.learning_rate,
global_step=global_step - FLAGS.warmup_steps,
decay_steps=FLAGS.train_steps - FLAGS.warmup_steps,
alpha=FLAGS.min_lr_ratio)
else:
raise ValueError(FLAGS.decay_method)
learning_rate = tf.where(global_step < FLAGS.warmup_steps,
warmup_lr, decay_lr)
if (FLAGS.weight_decay > 0 and not FLAGS.use_tpu and
FLAGS.num_core_per_host > 1):
raise ValueError("Do not support `weight_decay > 0` with multi-gpu "
"training so far.")
if FLAGS.weight_decay == 0:
optimizer = tf.train.AdamOptimizer(
learning_rate=learning_rate,
epsilon=FLAGS.adam_epsilon)
else:
optimizer = AdamWeightDecayOptimizer(
learning_rate=learning_rate,
epsilon=FLAGS.adam_epsilon,
exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"],
weight_decay_rate=FLAGS.weight_decay)
if FLAGS.use_tpu:
optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
if grads_and_vars is None:
grads_and_vars = optimizer.compute_gradients(total_loss)
gradients, variables = zip(*grads_and_vars)
clipped, gnorm = tf.clip_by_global_norm(gradients, FLAGS.clip)
if getattr(FLAGS, "lr_layer_decay_rate", 1.0) != 1.0:
n_layer = 0
for i in range(len(clipped)):
m = re.search(r"model/transformer/layer_(\d+?)/", variables[i].name)
if not m: continue
n_layer = max(n_layer, int(m.group(1)) + 1)
for i in range(len(clipped)):
for l in range(n_layer):
if "model/transformer/layer_{}/".format(l) in variables[i].name:
abs_rate = FLAGS.lr_layer_decay_rate ** (n_layer - 1 - l)
clipped[i] *= abs_rate
tf.logging.info("Apply mult {:.4f} to layer-{} grad of {}".format(
abs_rate, l, variables[i].name))
break
train_op = optimizer.apply_gradients(
zip(clipped, variables), global_step=global_step)
# Manually increment `global_step` for AdamWeightDecayOptimizer
if FLAGS.weight_decay > 0:
new_global_step = global_step + 1
train_op = tf.group(train_op, [global_step.assign(new_global_step)])
return train_op, learning_rate, gnorm
def clean_ckpt(_):
input_ckpt = FLAGS.clean_input_ckpt
output_model_dir = FLAGS.clean_output_model_dir
tf.reset_default_graph()
var_list = tf.contrib.framework.list_variables(input_ckpt)
var_values, var_dtypes = {}, {}
for (name, shape) in var_list:
if not name.startswith("global_step") and "adam" not in name.lower():
var_values[name] = None
tf.logging.info("Include {}".format(name))
else:
tf.logging.info("Exclude {}".format(name))
tf.logging.info("Loading from {}".format(input_ckpt))
reader = tf.contrib.framework.load_checkpoint(input_ckpt)
for name in var_values:
tensor = reader.get_tensor(name)
var_dtypes[name] = tensor.dtype
var_values[name] = tensor
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
tf_vars = [
tf.get_variable(v, shape=var_values[v].shape, dtype=var_dtypes[v])
for v in var_values
]
placeholders = [tf.placeholder(v.dtype, shape=v.shape) for v in tf_vars]
assign_ops = [tf.assign(v, p) for (v, p) in zip(tf_vars, placeholders)]
global_step = tf.Variable(
0, name="global_step", trainable=False, dtype=tf.int64)
saver = tf.train.Saver(tf.all_variables())
if not tf.gfile.Exists(output_model_dir):
tf.gfile.MakeDirs(output_model_dir)
# Build a model consisting only of variables, set them to the average values.
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for p, assign_op, (name, value) in zip(placeholders, assign_ops,
six.iteritems(var_values)):
sess.run(assign_op, {p: value})
# Use the built saver to save the averaged checkpoint.
saver.save(sess, join(output_model_dir, "model.ckpt"),
global_step=global_step)
def avg_checkpoints(model_dir, output_model_dir, last_k):
tf.reset_default_graph()
checkpoint_state = tf.train.get_checkpoint_state(model_dir)
checkpoints = checkpoint_state.all_model_checkpoint_paths[- last_k:]
var_list = tf.contrib.framework.list_variables(checkpoints[0])
var_values, var_dtypes = {}, {}
for (name, shape) in var_list:
if not name.startswith("global_step"):
var_values[name] = np.zeros(shape)
for checkpoint in checkpoints:
reader = tf.contrib.framework.load_checkpoint(checkpoint)
for name in var_values:
tensor = reader.get_tensor(name)
var_dtypes[name] = tensor.dtype
var_values[name] += tensor
tf.logging.info("Read from checkpoint %s", checkpoint)
for name in var_values: # Average.
var_values[name] /= len(checkpoints)
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
tf_vars = [
tf.get_variable(v, shape=var_values[v].shape, dtype=var_dtypes[v])
for v in var_values
]
placeholders = [tf.placeholder(v.dtype, shape=v.shape) for v in tf_vars]
assign_ops = [tf.assign(v, p) for (v, p) in zip(tf_vars, placeholders)]
global_step = tf.Variable(
0, name="global_step", trainable=False, dtype=tf.int64)
saver = tf.train.Saver(tf.all_variables())
# Build a model consisting only of variables, set them to the average values.
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for p, assign_op, (name, value) in zip(placeholders, assign_ops,
six.iteritems(var_values)):
sess.run(assign_op, {p: value})
# Use the built saver to save the averaged checkpoint.
saver.save(sess, join(output_model_dir, "model.ckpt"),
global_step=global_step)
def get_assignment_map_from_checkpoint(tvars, init_checkpoint):
"""Compute the union of the current variables and checkpoint variables."""
assignment_map = {}
initialized_variable_names = {}
name_to_variable = collections.OrderedDict()
for var in tvars:
name = var.name
m = re.match("^(.*):\\d+$", name)
if m is not None:
name = m.group(1)
name_to_variable[name] = var
init_vars = tf.train.list_variables(init_checkpoint)
assignment_map = collections.OrderedDict()
for x in init_vars:
(name, var) = (x[0], x[1])
# tf.logging.info('original name: %s', name)
if name not in name_to_variable:
continue
# assignment_map[name] = name
assignment_map[name] = name_to_variable[name]
initialized_variable_names[name] = 1
initialized_variable_names[name + ":0"] = 1
return (assignment_map, initialized_variable_names)
class AdamWeightDecayOptimizer(tf.train.Optimizer):
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self,
learning_rate,
weight_decay_rate=0.0,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-6,
exclude_from_weight_decay=None,
include_in_weight_decay=["r_s_bias", "r_r_bias", "r_w_bias"],
name="AdamWeightDecayOptimizer"):
"""Constructs a AdamWeightDecayOptimizer."""
super(AdamWeightDecayOptimizer, self).__init__(False, name)
self.learning_rate = learning_rate
self.weight_decay_rate = weight_decay_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
self.exclude_from_weight_decay = exclude_from_weight_decay
self.include_in_weight_decay = include_in_weight_decay
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""See base class."""
assignments = []
for (grad, param) in grads_and_vars:
if grad is None or param is None:
continue
param_name = self._get_variable_name(param.name)
m = tf.get_variable(
name=param_name + "/adam_m",
shape=param.shape.as_list(),
dtype=tf.float32,
trainable=False,
initializer=tf.zeros_initializer())
v = tf.get_variable(
name=param_name + "/adam_v",
shape=param.shape.as_list(),
dtype=tf.float32,
trainable=False,
initializer=tf.zeros_initializer())
# Standard Adam update.
next_m = (
tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad))
next_v = (
tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2,
tf.square(grad)))
update = next_m / (tf.sqrt(next_v) + self.epsilon)
# Just adding the square of the weights to the loss function is *not*
# the correct way of using L2 regularization/weight decay with Adam,
# since that will interact with the m and v parameters in strange ways.
#
# Instead we want ot decay the weights in a manner that doesn't interact
# with the m/v parameters. This is equivalent to adding the square
# of the weights to the loss with plain (non-momentum) SGD.
if self._do_use_weight_decay(param_name):
update += self.weight_decay_rate * param
update_with_lr = self.learning_rate * update
next_param = param - update_with_lr
assignments.extend(
[param.assign(next_param),
m.assign(next_m),
v.assign(next_v)])
return tf.group(*assignments, name=name)
def _do_use_weight_decay(self, param_name):
"""Whether to use L2 weight decay for `param_name`."""
if not self.weight_decay_rate:
return False
for r in self.include_in_weight_decay:
if re.search(r, param_name) is not None:
return True
if self.exclude_from_weight_decay:
for r in self.exclude_from_weight_decay:
if re.search(r, param_name) is not None:
tf.logging.info('Adam WD excludes {}'.format(param_name))
return False
return True
def _get_variable_name(self, param_name):
"""Get the variable name from the tensor name."""
m = re.match("^(.*):\\d+$", param_name)
if m is not None:
param_name = m.group(1)
return param_name
if __name__ == "__main__":
flags.DEFINE_string("clean_input_ckpt", "", "input ckpt for cleaning")
flags.DEFINE_string("clean_output_model_dir", "", "output dir for cleaned ckpt")
FLAGS = flags.FLAGS
tf.app.run(clean_ckpt)
| 14,078 | 34.1975 | 82 | py |
CLUE | CLUE-master/baselines/models/xlnet/prepro_utils.py | # coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unicodedata
import six
from functools import partial
SPIECE_UNDERLINE = '▁'
def printable_text(text):
"""Returns text encoded in a way suitable for print or `tf.logging`."""
# These functions want `str` for both Python2 and Python3, but in one case
# it's a Unicode string and in the other it's a byte string.
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text
elif isinstance(text, unicode):
return text.encode("utf-8")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?")
def print_(*args):
new_args = []
for arg in args:
if isinstance(arg, list):
s = [printable_text(i) for i in arg]
s = ' '.join(s)
new_args.append(s)
else:
new_args.append(printable_text(arg))
print(*new_args)
def preprocess_text(inputs, lower=False, remove_space=True, keep_accents=False):
if remove_space:
outputs = ' '.join(inputs.strip().split())
else:
outputs = inputs
outputs = outputs.replace("``", '"').replace("''", '"')
if six.PY2 and isinstance(outputs, str):
outputs = outputs.decode('utf-8')
if not keep_accents:
outputs = unicodedata.normalize('NFKD', outputs)
outputs = ''.join([c for c in outputs if not unicodedata.combining(c)])
if lower:
outputs = outputs.lower()
return outputs
def encode_pieces(sp_model, text, return_unicode=True, sample=False):
# return_unicode is used only for py2
# note(zhiliny): in some systems, sentencepiece only accepts str for py2
if six.PY2 and isinstance(text, unicode):
text = text.encode('utf-8')
if not sample:
pieces = sp_model.EncodeAsPieces(text)
else:
pieces = sp_model.SampleEncodeAsPieces(text, 64, 0.1)
new_pieces = []
for piece in pieces:
if len(piece) > 1 and piece[-1] == ',' and piece[-2].isdigit():
cur_pieces = sp_model.EncodeAsPieces(
piece[:-1].replace(SPIECE_UNDERLINE, ''))
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
if len(cur_pieces[0]) == 1:
cur_pieces = cur_pieces[1:]
else:
cur_pieces[0] = cur_pieces[0][1:]
cur_pieces.append(piece[-1])
new_pieces.extend(cur_pieces)
else:
new_pieces.append(piece)
# note(zhiliny): convert back to unicode for py2
if six.PY2 and return_unicode:
ret_pieces = []
for piece in new_pieces:
if isinstance(piece, str):
piece = piece.decode('utf-8')
ret_pieces.append(piece)
new_pieces = ret_pieces
return new_pieces
def encode_ids(sp_model, text, sample=False):
pieces = encode_pieces(sp_model, text, return_unicode=False, sample=sample)
ids = [sp_model.PieceToId(piece) for piece in pieces]
return ids
if __name__ == '__main__':
import sentencepiece as spm
sp = spm.SentencePieceProcessor()
sp.load('sp10m.uncased.v3.model')
print_(u'I was born in 2000, and this is falsé.')
print_(u'ORIGINAL', sp.EncodeAsPieces(u'I was born in 2000, and this is falsé.'))
print_(u'OURS', encode_pieces(sp, u'I was born in 2000, and this is falsé.'))
print(encode_ids(sp, u'I was born in 2000, and this is falsé.'))
print_('')
prepro_func = partial(preprocess_text, lower=True)
print_(prepro_func('I was born in 2000, and this is falsé.'))
print_('ORIGINAL', sp.EncodeAsPieces(prepro_func('I was born in 2000, and this is falsé.')))
print_('OURS', encode_pieces(sp, prepro_func('I was born in 2000, and this is falsé.')))
print(encode_ids(sp, prepro_func('I was born in 2000, and this is falsé.')))
print_('')
print_('I was born in 2000, and this is falsé.')
print_('ORIGINAL', sp.EncodeAsPieces('I was born in 2000, and this is falsé.'))
print_('OURS', encode_pieces(sp, 'I was born in 2000, and this is falsé.'))
print(encode_ids(sp, 'I was born in 2000, and this is falsé.'))
print_('')
print_('I was born in 92000, and this is falsé.')
print_('ORIGINAL', sp.EncodeAsPieces('I was born in 92000, and this is falsé.'))
print_('OURS', encode_pieces(sp, 'I was born in 92000, and this is falsé.'))
print(encode_ids(sp, 'I was born in 92000, and this is falsé.'))
| 4,528 | 31.582734 | 94 | py |
CLUE | CLUE-master/baselines/models/xlnet/modeling.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def gelu(x):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
`x` with the GELU activation applied.
"""
cdf = 0.5 * (1.0 + tf.tanh(
(np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
return x * cdf
def embedding_lookup(x, n_token, d_embed, initializer, use_tpu=True,
scope='embedding', reuse=None, dtype=tf.float32):
"""TPU and GPU embedding_lookup function."""
with tf.variable_scope(scope, reuse=reuse):
lookup_table = tf.get_variable('lookup_table', [n_token, d_embed],
dtype=dtype, initializer=initializer)
if use_tpu:
one_hot_idx = tf.one_hot(x, n_token, dtype=dtype)
if one_hot_idx.shape.ndims == 2:
return tf.einsum('in,nd->id', one_hot_idx, lookup_table), lookup_table
else:
return tf.einsum('ibn,nd->ibd', one_hot_idx, lookup_table), lookup_table
else:
return tf.nn.embedding_lookup(lookup_table, x), lookup_table
def positional_embedding(pos_seq, inv_freq, bsz=None):
sinusoid_inp = tf.einsum('i,d->id', pos_seq, inv_freq)
pos_emb = tf.concat([tf.sin(sinusoid_inp), tf.cos(sinusoid_inp)], -1)
pos_emb = pos_emb[:, None, :]
if bsz is not None:
pos_emb = tf.tile(pos_emb, [1, bsz, 1])
return pos_emb
def positionwise_ffn(inp, d_model, d_inner, dropout, kernel_initializer,
activation_type='relu', scope='ff', is_training=True,
reuse=None):
"""Position-wise Feed-forward Network."""
if activation_type == 'relu':
activation = tf.nn.relu
elif activation_type == 'gelu':
activation = gelu
else:
raise ValueError('Unsupported activation type {}'.format(activation_type))
output = inp
with tf.variable_scope(scope, reuse=reuse):
output = tf.layers.dense(output, d_inner, activation=activation,
kernel_initializer=kernel_initializer,
name='layer_1')
output = tf.layers.dropout(output, dropout, training=is_training,
name='drop_1')
output = tf.layers.dense(output, d_model,
kernel_initializer=kernel_initializer,
name='layer_2')
output = tf.layers.dropout(output, dropout, training=is_training,
name='drop_2')
output = tf.contrib.layers.layer_norm(output + inp, begin_norm_axis=-1,
scope='LayerNorm')
return output
def head_projection(h, d_model, n_head, d_head, kernel_initializer, name):
"""Project hidden states to a specific head with a 4D-shape."""
proj_weight = tf.get_variable('{}/kernel'.format(name),
[d_model, n_head, d_head], dtype=h.dtype,
initializer=kernel_initializer)
head = tf.einsum('ibh,hnd->ibnd', h, proj_weight)
return head
def post_attention(h, attn_vec, d_model, n_head, d_head, dropout, is_training,
kernel_initializer, residual=True):
"""Post-attention processing."""
# post-attention projection (back to `d_model`)
proj_o = tf.get_variable('o/kernel', [d_model, n_head, d_head],
dtype=h.dtype, initializer=kernel_initializer)
attn_out = tf.einsum('ibnd,hnd->ibh', attn_vec, proj_o)
attn_out = tf.layers.dropout(attn_out, dropout, training=is_training)
if residual:
output = tf.contrib.layers.layer_norm(attn_out + h, begin_norm_axis=-1,
scope='LayerNorm')
else:
output = tf.contrib.layers.layer_norm(attn_out, begin_norm_axis=-1,
scope='LayerNorm')
return output
def abs_attn_core(q_head, k_head, v_head, attn_mask, dropatt, is_training,
scale):
"""Core absolute positional attention operations."""
attn_score = tf.einsum('ibnd,jbnd->ijbn', q_head, k_head)
attn_score *= scale
if attn_mask is not None:
attn_score = attn_score - 1e30 * attn_mask
# attention probability
attn_prob = tf.nn.softmax(attn_score, 1)
attn_prob = tf.layers.dropout(attn_prob, dropatt, training=is_training)
# attention output
attn_vec = tf.einsum('ijbn,jbnd->ibnd', attn_prob, v_head)
return attn_vec
def rel_attn_core(q_head, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat,
r_w_bias, r_r_bias, r_s_bias, attn_mask, dropatt, is_training,
scale):
"""Core relative positional attention operations."""
# content based attention score
ac = tf.einsum('ibnd,jbnd->ijbn', q_head + r_w_bias, k_head_h)
# position based attention score
bd = tf.einsum('ibnd,jbnd->ijbn', q_head + r_r_bias, k_head_r)
bd = rel_shift(bd, klen=tf.shape(ac)[1])
# segment based attention score
if seg_mat is None:
ef = 0
else:
ef = tf.einsum('ibnd,snd->ibns', q_head + r_s_bias, seg_embed)
ef = tf.einsum('ijbs,ibns->ijbn', seg_mat, ef)
# merge attention scores and perform masking
attn_score = (ac + bd + ef) * scale
if attn_mask is not None:
# attn_score = attn_score * (1 - attn_mask) - 1e30 * attn_mask
attn_score = attn_score - 1e30 * attn_mask
# attention probability
attn_prob = tf.nn.softmax(attn_score, 1)
attn_prob = tf.layers.dropout(attn_prob, dropatt, training=is_training)
# attention output
attn_vec = tf.einsum('ijbn,jbnd->ibnd', attn_prob, v_head_h)
return attn_vec
def rel_shift(x, klen=-1):
"""perform relative shift to form the relative attention score."""
x_size = tf.shape(x)
x = tf.reshape(x, [x_size[1], x_size[0], x_size[2], x_size[3]])
x = tf.slice(x, [1, 0, 0, 0], [-1, -1, -1, -1])
x = tf.reshape(x, [x_size[0], x_size[1] - 1, x_size[2], x_size[3]])
x = tf.slice(x, [0, 0, 0, 0], [-1, klen, -1, -1])
return x
def _create_mask(qlen, mlen, dtype=tf.float32, same_length=False):
"""create causal attention mask."""
attn_mask = tf.ones([qlen, qlen], dtype=dtype)
mask_u = tf.matrix_band_part(attn_mask, 0, -1)
mask_dia = tf.matrix_band_part(attn_mask, 0, 0)
attn_mask_pad = tf.zeros([qlen, mlen], dtype=dtype)
ret = tf.concat([attn_mask_pad, mask_u - mask_dia], 1)
if same_length:
mask_l = tf.matrix_band_part(attn_mask, -1, 0)
ret = tf.concat([ret[:, :qlen] + mask_l - mask_dia, ret[:, qlen:]], 1)
return ret
def _cache_mem(curr_out, prev_mem, mem_len, reuse_len=None):
"""cache hidden states into memory."""
if mem_len is None or mem_len == 0:
return None
else:
if reuse_len is not None and reuse_len > 0:
curr_out = curr_out[:reuse_len]
if prev_mem is None:
new_mem = curr_out[-mem_len:]
else:
new_mem = tf.concat([prev_mem, curr_out], 0)[-mem_len:]
return tf.stop_gradient(new_mem)
def relative_positional_encoding(qlen, klen, d_model, clamp_len, attn_type,
bi_data, bsz=None, dtype=None):
"""create relative positional encoding."""
freq_seq = tf.range(0, d_model, 2.0)
if dtype is not None and dtype != tf.float32:
freq_seq = tf.cast(freq_seq, dtype=dtype)
inv_freq = 1 / (10000 ** (freq_seq / d_model))
if attn_type == 'bi':
# beg, end = klen - 1, -qlen
beg, end = klen, -qlen
elif attn_type == 'uni':
# beg, end = klen - 1, -1
beg, end = klen, -1
else:
raise ValueError('Unknown `attn_type` {}.'.format(attn_type))
if bi_data:
fwd_pos_seq = tf.range(beg, end, -1.0)
bwd_pos_seq = tf.range(-beg, -end, 1.0)
if dtype is not None and dtype != tf.float32:
fwd_pos_seq = tf.cast(fwd_pos_seq, dtype=dtype)
bwd_pos_seq = tf.cast(bwd_pos_seq, dtype=dtype)
if clamp_len > 0:
fwd_pos_seq = tf.clip_by_value(fwd_pos_seq, -clamp_len, clamp_len)
bwd_pos_seq = tf.clip_by_value(bwd_pos_seq, -clamp_len, clamp_len)
if bsz is not None:
# With bi_data, the batch size should be divisible by 2.
assert bsz%2 == 0
fwd_pos_emb = positional_embedding(fwd_pos_seq, inv_freq, bsz//2)
bwd_pos_emb = positional_embedding(bwd_pos_seq, inv_freq, bsz//2)
else:
fwd_pos_emb = positional_embedding(fwd_pos_seq, inv_freq)
bwd_pos_emb = positional_embedding(bwd_pos_seq, inv_freq)
pos_emb = tf.concat([fwd_pos_emb, bwd_pos_emb], axis=1)
else:
fwd_pos_seq = tf.range(beg, end, -1.0)
if dtype is not None and dtype != tf.float32:
fwd_pos_seq = tf.cast(fwd_pos_seq, dtype=dtype)
if clamp_len > 0:
fwd_pos_seq = tf.clip_by_value(fwd_pos_seq, -clamp_len, clamp_len)
pos_emb = positional_embedding(fwd_pos_seq, inv_freq, bsz)
return pos_emb
def multihead_attn(q, k, v, attn_mask, d_model, n_head, d_head, dropout,
dropatt, is_training, kernel_initializer, residual=True,
scope='abs_attn', reuse=None):
"""Standard multi-head attention with absolute positional embedding."""
scale = 1 / (d_head ** 0.5)
with tf.variable_scope(scope, reuse=reuse):
# attention heads
q_head = head_projection(
q, d_model, n_head, d_head, kernel_initializer, 'q')
k_head = head_projection(
k, d_model, n_head, d_head, kernel_initializer, 'k')
v_head = head_projection(
v, d_model, n_head, d_head, kernel_initializer, 'v')
# attention vector
attn_vec = abs_attn_core(q_head, k_head, v_head, attn_mask, dropatt,
is_training, scale)
# post processing
output = post_attention(v, attn_vec, d_model, n_head, d_head, dropout,
is_training, kernel_initializer, residual)
return output
def rel_multihead_attn(h, r, r_w_bias, r_r_bias, seg_mat, r_s_bias, seg_embed,
attn_mask, mems, d_model, n_head, d_head, dropout,
dropatt, is_training, kernel_initializer,
scope='rel_attn', reuse=None):
"""Multi-head attention with relative positional encoding."""
scale = 1 / (d_head ** 0.5)
with tf.variable_scope(scope, reuse=reuse):
if mems is not None and mems.shape.ndims > 1:
cat = tf.concat([mems, h], 0)
else:
cat = h
# content heads
q_head_h = head_projection(
h, d_model, n_head, d_head, kernel_initializer, 'q')
k_head_h = head_projection(
cat, d_model, n_head, d_head, kernel_initializer, 'k')
v_head_h = head_projection(
cat, d_model, n_head, d_head, kernel_initializer, 'v')
# positional heads
k_head_r = head_projection(
r, d_model, n_head, d_head, kernel_initializer, 'r')
# core attention ops
attn_vec = rel_attn_core(
q_head_h, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias,
r_r_bias, r_s_bias, attn_mask, dropatt, is_training, scale)
# post processing
output = post_attention(h, attn_vec, d_model, n_head, d_head, dropout,
is_training, kernel_initializer)
return output
def two_stream_rel_attn(h, g, r, mems, r_w_bias, r_r_bias, seg_mat, r_s_bias,
seg_embed, attn_mask_h, attn_mask_g, target_mapping,
d_model, n_head, d_head, dropout, dropatt, is_training,
kernel_initializer, scope='rel_attn'):
"""Two-stream attention with relative positional encoding."""
scale = 1 / (d_head ** 0.5)
with tf.variable_scope(scope, reuse=False):
# content based attention score
if mems is not None and mems.shape.ndims > 1:
cat = tf.concat([mems, h], 0)
else:
cat = h
# content-based key head
k_head_h = head_projection(
cat, d_model, n_head, d_head, kernel_initializer, 'k')
# content-based value head
v_head_h = head_projection(
cat, d_model, n_head, d_head, kernel_initializer, 'v')
# position-based key head
k_head_r = head_projection(
r, d_model, n_head, d_head, kernel_initializer, 'r')
##### h-stream
# content-stream query head
q_head_h = head_projection(
h, d_model, n_head, d_head, kernel_initializer, 'q')
# core attention ops
attn_vec_h = rel_attn_core(
q_head_h, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias,
r_r_bias, r_s_bias, attn_mask_h, dropatt, is_training, scale)
# post processing
output_h = post_attention(h, attn_vec_h, d_model, n_head, d_head, dropout,
is_training, kernel_initializer)
with tf.variable_scope(scope, reuse=True):
##### g-stream
# query-stream query head
q_head_g = head_projection(
g, d_model, n_head, d_head, kernel_initializer, 'q')
# core attention ops
if target_mapping is not None:
q_head_g = tf.einsum('mbnd,mlb->lbnd', q_head_g, target_mapping)
attn_vec_g = rel_attn_core(
q_head_g, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias,
r_r_bias, r_s_bias, attn_mask_g, dropatt, is_training, scale)
attn_vec_g = tf.einsum('lbnd,mlb->mbnd', attn_vec_g, target_mapping)
else:
attn_vec_g = rel_attn_core(
q_head_g, k_head_h, v_head_h, k_head_r, seg_embed, seg_mat, r_w_bias,
r_r_bias, r_s_bias, attn_mask_g, dropatt, is_training, scale)
# post processing
output_g = post_attention(g, attn_vec_g, d_model, n_head, d_head, dropout,
is_training, kernel_initializer)
return output_h, output_g
def transformer_xl(inp_k, n_token, n_layer, d_model, n_head,
d_head, d_inner, dropout, dropatt, attn_type,
bi_data, initializer, is_training, mem_len=None,
inp_q=None, mems=None,
same_length=False, clamp_len=-1, untie_r=False,
use_tpu=True, input_mask=None,
perm_mask=None, seg_id=None, reuse_len=None,
ff_activation='relu', target_mapping=None,
use_bfloat16=False, scope='transformer', **kwargs):
"""
Defines a Transformer-XL computation graph with additional
support for XLNet.
Args:
inp_k: int32 Tensor in shape [len, bsz], the input token IDs.
seg_id: int32 Tensor in shape [len, bsz], the input segment IDs.
input_mask: float32 Tensor in shape [len, bsz], the input mask.
0 for real tokens and 1 for padding.
mems: a list of float32 Tensors in shape [mem_len, bsz, d_model], memory
from previous batches. The length of the list equals n_layer.
If None, no memory is used.
perm_mask: float32 Tensor in shape [len, len, bsz].
If perm_mask[i, j, k] = 0, i attend to j in batch k;
if perm_mask[i, j, k] = 1, i does not attend to j in batch k.
If None, each position attends to all the others.
target_mapping: float32 Tensor in shape [num_predict, len, bsz].
If target_mapping[i, j, k] = 1, the i-th predict in batch k is
on the j-th token.
Only used during pretraining for partial prediction.
Set to None during finetuning.
inp_q: float32 Tensor in shape [len, bsz].
1 for tokens with losses and 0 for tokens without losses.
Only used during pretraining for two-stream attention.
Set to None during finetuning.
n_layer: int, the number of layers.
d_model: int, the hidden size.
n_head: int, the number of attention heads.
d_head: int, the dimension size of each attention head.
d_inner: int, the hidden size in feed-forward layers.
ff_activation: str, "relu" or "gelu".
untie_r: bool, whether to untie the biases in attention.
n_token: int, the vocab size.
is_training: bool, whether in training mode.
use_tpu: bool, whether TPUs are used.
use_bfloat16: bool, use bfloat16 instead of float32.
dropout: float, dropout rate.
dropatt: float, dropout rate on attention probabilities.
init: str, the initialization scheme, either "normal" or "uniform".
init_range: float, initialize the parameters with a uniform distribution
in [-init_range, init_range]. Only effective when init="uniform".
init_std: float, initialize the parameters with a normal distribution
with mean 0 and stddev init_std. Only effective when init="normal".
mem_len: int, the number of tokens to cache.
reuse_len: int, the number of tokens in the currect batch to be cached
and reused in the future.
bi_data: bool, whether to use bidirectional input pipeline.
Usually set to True during pretraining and False during finetuning.
clamp_len: int, clamp all relative distances larger than clamp_len.
-1 means no clamping.
same_length: bool, whether to use the same attention length for each token.
summary_type: str, "last", "first", "mean", or "attn". The method
to pool the input to get a vector representation.
initializer: A tf initializer.
scope: scope name for the computation graph.
"""
tf.logging.info('memory input {}'.format(mems))
tf_float = tf.bfloat16 if use_bfloat16 else tf.float32
tf.logging.info('Use float type {}'.format(tf_float))
new_mems = []
with tf.variable_scope(scope):
if untie_r:
r_w_bias = tf.get_variable('r_w_bias', [n_layer, n_head, d_head],
dtype=tf_float, initializer=initializer)
r_r_bias = tf.get_variable('r_r_bias', [n_layer, n_head, d_head],
dtype=tf_float, initializer=initializer)
else:
r_w_bias = tf.get_variable('r_w_bias', [n_head, d_head],
dtype=tf_float, initializer=initializer)
r_r_bias = tf.get_variable('r_r_bias', [n_head, d_head],
dtype=tf_float, initializer=initializer)
bsz = tf.shape(inp_k)[1]
qlen = tf.shape(inp_k)[0]
mlen = tf.shape(mems[0])[0] if mems is not None else 0
klen = mlen + qlen
##### Attention mask
# causal attention mask
if attn_type == 'uni':
attn_mask = _create_mask(qlen, mlen, tf_float, same_length)
attn_mask = attn_mask[:, :, None, None]
elif attn_type == 'bi':
attn_mask = None
else:
raise ValueError('Unsupported attention type: {}'.format(attn_type))
# data mask: input mask & perm mask
if input_mask is not None and perm_mask is not None:
data_mask = input_mask[None] + perm_mask
elif input_mask is not None and perm_mask is None:
data_mask = input_mask[None]
elif input_mask is None and perm_mask is not None:
data_mask = perm_mask
else:
data_mask = None
if data_mask is not None:
# all mems can be attended to
mems_mask = tf.zeros([tf.shape(data_mask)[0], mlen, bsz],
dtype=tf_float)
data_mask = tf.concat([mems_mask, data_mask], 1)
if attn_mask is None:
attn_mask = data_mask[:, :, :, None]
else:
attn_mask += data_mask[:, :, :, None]
if attn_mask is not None:
attn_mask = tf.cast(attn_mask > 0, dtype=tf_float)
if attn_mask is not None:
non_tgt_mask = -tf.eye(qlen, dtype=tf_float)
non_tgt_mask = tf.concat([tf.zeros([qlen, mlen], dtype=tf_float),
non_tgt_mask], axis=-1)
non_tgt_mask = tf.cast((attn_mask + non_tgt_mask[:, :, None, None]) > 0,
dtype=tf_float)
else:
non_tgt_mask = None
##### Word embedding
word_emb_k, lookup_table = embedding_lookup(
x=inp_k,
n_token=n_token,
d_embed=d_model,
initializer=initializer,
use_tpu=use_tpu,
dtype=tf_float,
scope='word_embedding')
if inp_q is not None:
with tf.variable_scope('mask_emb'):
mask_emb = tf.get_variable('mask_emb', [1, 1, d_model], dtype=tf_float)
if target_mapping is not None:
word_emb_q = tf.tile(mask_emb, [tf.shape(target_mapping)[0], bsz, 1])
else:
inp_q_ext = inp_q[:, :, None]
word_emb_q = inp_q_ext * mask_emb + (1 - inp_q_ext) * word_emb_k
output_h = tf.layers.dropout(word_emb_k, dropout, training=is_training)
if inp_q is not None:
output_g = tf.layers.dropout(word_emb_q, dropout, training=is_training)
##### Segment embedding
if seg_id is not None:
if untie_r:
r_s_bias = tf.get_variable('r_s_bias', [n_layer, n_head, d_head],
dtype=tf_float, initializer=initializer)
else:
# default case (tie)
r_s_bias = tf.get_variable('r_s_bias', [n_head, d_head],
dtype=tf_float, initializer=initializer)
seg_embed = tf.get_variable('seg_embed', [n_layer, 2, n_head, d_head],
dtype=tf_float, initializer=initializer)
# Convert `seg_id` to one-hot `seg_mat`
mem_pad = tf.zeros([mlen, bsz], dtype=tf.int32)
cat_ids = tf.concat([mem_pad, seg_id], 0)
# `1` indicates not in the same segment [qlen x klen x bsz]
seg_mat = tf.cast(
tf.logical_not(tf.equal(seg_id[:, None], cat_ids[None, :])),
tf.int32)
seg_mat = tf.one_hot(seg_mat, 2, dtype=tf_float)
else:
seg_mat = None
##### Positional encoding
pos_emb = relative_positional_encoding(
qlen, klen, d_model, clamp_len, attn_type, bi_data,
bsz=bsz, dtype=tf_float)
pos_emb = tf.layers.dropout(pos_emb, dropout, training=is_training)
##### Attention layers
if mems is None:
mems = [None] * n_layer
for i in range(n_layer):
# cache new mems
new_mems.append(_cache_mem(output_h, mems[i], mem_len, reuse_len))
# segment bias
if seg_id is None:
r_s_bias_i = None
seg_embed_i = None
else:
r_s_bias_i = r_s_bias if not untie_r else r_s_bias[i]
seg_embed_i = seg_embed[i]
with tf.variable_scope('layer_{}'.format(i)):
if inp_q is not None:
output_h, output_g = two_stream_rel_attn(
h=output_h,
g=output_g,
r=pos_emb,
r_w_bias=r_w_bias if not untie_r else r_w_bias[i],
r_r_bias=r_r_bias if not untie_r else r_r_bias[i],
seg_mat=seg_mat,
r_s_bias=r_s_bias_i,
seg_embed=seg_embed_i,
attn_mask_h=non_tgt_mask,
attn_mask_g=attn_mask,
mems=mems[i],
target_mapping=target_mapping,
d_model=d_model,
n_head=n_head,
d_head=d_head,
dropout=dropout,
dropatt=dropatt,
is_training=is_training,
kernel_initializer=initializer)
reuse = True
else:
reuse = False
output_h = rel_multihead_attn(
h=output_h,
r=pos_emb,
r_w_bias=r_w_bias if not untie_r else r_w_bias[i],
r_r_bias=r_r_bias if not untie_r else r_r_bias[i],
seg_mat=seg_mat,
r_s_bias=r_s_bias_i,
seg_embed=seg_embed_i,
attn_mask=non_tgt_mask,
mems=mems[i],
d_model=d_model,
n_head=n_head,
d_head=d_head,
dropout=dropout,
dropatt=dropatt,
is_training=is_training,
kernel_initializer=initializer,
reuse=reuse)
if inp_q is not None:
output_g = positionwise_ffn(
inp=output_g,
d_model=d_model,
d_inner=d_inner,
dropout=dropout,
kernel_initializer=initializer,
activation_type=ff_activation,
is_training=is_training)
output_h = positionwise_ffn(
inp=output_h,
d_model=d_model,
d_inner=d_inner,
dropout=dropout,
kernel_initializer=initializer,
activation_type=ff_activation,
is_training=is_training,
reuse=reuse)
if inp_q is not None:
output = tf.layers.dropout(output_g, dropout, training=is_training)
else:
output = tf.layers.dropout(output_h, dropout, training=is_training)
return output, new_mems, lookup_table
def lm_loss(hidden, target, n_token, d_model, initializer, lookup_table=None,
tie_weight=False, bi_data=True, use_tpu=False):
"""doc."""
with tf.variable_scope('lm_loss'):
if tie_weight:
assert lookup_table is not None, \
'lookup_table cannot be None for tie_weight'
softmax_w = lookup_table
else:
softmax_w = tf.get_variable('weight', [n_token, d_model],
dtype=hidden.dtype, initializer=initializer)
softmax_b = tf.get_variable('bias', [n_token], dtype=hidden.dtype,
initializer=tf.zeros_initializer())
logits = tf.einsum('ibd,nd->ibn', hidden, softmax_w) + softmax_b
if use_tpu:
one_hot_target = tf.one_hot(target, n_token, dtype=logits.dtype)
loss = -tf.reduce_sum(tf.nn.log_softmax(logits) * one_hot_target, -1)
else:
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=target,
logits=logits)
return loss
def summarize_sequence(summary_type, hidden, d_model, n_head, d_head, dropout,
dropatt, input_mask, is_training, initializer,
scope=None, reuse=None, use_proj=True):
"""
Different classification tasks may not may not share the same parameters
to summarize the sequence features.
If shared, one can keep the `scope` to the default value `None`.
Otherwise, one should specify a different `scope` for each task.
"""
with tf.variable_scope(scope, 'sequnece_summary', reuse=reuse):
if summary_type == 'last':
summary = hidden[-1]
elif summary_type == 'first':
summary = hidden[0]
elif summary_type == 'mean':
summary = tf.reduce_mean(hidden, axis=0)
elif summary_type == 'attn':
bsz = tf.shape(hidden)[1]
summary_bias = tf.get_variable('summary_bias', [d_model],
dtype=hidden.dtype,
initializer=initializer)
summary_bias = tf.tile(summary_bias[None, None], [1, bsz, 1])
if input_mask is not None:
input_mask = input_mask[None, :, :, None]
summary = multihead_attn(summary_bias, hidden, hidden, input_mask,
d_model, n_head, d_head, dropout, dropatt,
is_training, initializer, residual=False)
summary = summary[0]
else:
raise ValueError('Unsupported summary type {}'.format(summary_type))
# use another projection as in BERT
if use_proj:
summary = tf.layers.dense(
summary,
d_model,
activation=tf.tanh,
kernel_initializer=initializer,
name='summary')
# dropout
summary = tf.layers.dropout(
summary, dropout, training=is_training,
name='dropout')
return summary
def classification_loss(hidden, labels, n_class, initializer, scope, reuse=None,
return_logits=False):
"""
Different classification tasks should use different scope names to ensure
different dense layers (parameters) are used to produce the logits.
An exception will be in transfer learning, where one hopes to transfer
the classification weights.
"""
with tf.variable_scope(scope, reuse=reuse):
logits = tf.layers.dense(
hidden,
n_class,
kernel_initializer=initializer,
name='logit')
one_hot_target = tf.one_hot(labels, n_class, dtype=hidden.dtype)
loss = -tf.reduce_sum(tf.nn.log_softmax(logits) * one_hot_target, -1)
if return_logits:
return loss, logits
return loss
def regression_loss(hidden, labels, initializer, scope, reuse=None,
return_logits=False):
with tf.variable_scope(scope, reuse=reuse):
logits = tf.layers.dense(
hidden,
1,
kernel_initializer=initializer,
name='logit')
logits = tf.squeeze(logits, axis=-1)
loss = tf.square(logits - labels)
if return_logits:
return loss, logits
return loss
| 28,460 | 35.302296 | 80 | py |
CLUE | CLUE-master/baselines/models/xlnet/data_utils.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
import random
from absl import flags
import absl.logging as _logging # pylint: disable=unused-import
import numpy as np
import tensorflow as tf
from prepro_utils import preprocess_text, encode_ids
import sentencepiece as spm
special_symbols = {
"<unk>" : 0,
"<s>" : 1,
"</s>" : 2,
"<cls>" : 3,
"<sep>" : 4,
"<pad>" : 5,
"<mask>" : 6,
"<eod>" : 7,
"<eop>" : 8,
}
VOCAB_SIZE = 32000
UNK_ID = special_symbols["<unk>"]
CLS_ID = special_symbols["<cls>"]
SEP_ID = special_symbols["<sep>"]
MASK_ID = special_symbols["<mask>"]
EOD_ID = special_symbols["<eod>"]
def _int64_feature(values):
return tf.train.Feature(int64_list=tf.train.Int64List(value=values))
def _float_feature(values):
return tf.train.Feature(float_list=tf.train.FloatList(value=values))
def format_filename(prefix, bsz_per_host, seq_len, bi_data, suffix,
mask_alpha=5, mask_beta=1, reuse_len=None, uncased=False,
fixed_num_predict=None):
"""docs."""
if reuse_len is None:
reuse_len_str = ""
else:
reuse_len_str = "reuse-{}.".format(reuse_len)
if not uncased:
uncased_str = ""
else:
uncased_str = "uncased."
if bi_data:
bi_data_str = "bi"
else:
bi_data_str = "uni"
if fixed_num_predict is not None:
fnp_str = "fnp-{}.".format(fixed_num_predict)
else:
fnp_str = ""
file_name = "{}.bsz-{}.seqlen-{}.{}{}{}.alpha-{}.beta-{}.{}{}".format(
prefix, bsz_per_host, seq_len, reuse_len_str, uncased_str, bi_data_str,
mask_alpha, mask_beta, fnp_str, suffix)
return file_name
def _create_data(idx, input_paths):
# Load sentence-piece model
sp = spm.SentencePieceProcessor()
sp.Load(FLAGS.sp_path)
input_shards = []
total_line_cnt = 0
for input_path in input_paths:
input_data, sent_ids = [], []
sent_id, line_cnt = True, 0
tf.logging.info("Processing %s", input_path)
for line in tf.gfile.Open(input_path):
if line_cnt % 100000 == 0:
tf.logging.info("Loading line %d", line_cnt)
line_cnt += 1
if not line.strip():
if FLAGS.use_eod:
sent_id = not sent_id
cur_sent = [EOD_ID]
else:
continue
else:
if FLAGS.from_raw_text:
cur_sent = preprocess_text(line.strip(), lower=FLAGS.uncased)
cur_sent = encode_ids(sp, cur_sent)
else:
cur_sent = list(map(int, line.strip().split()))
input_data.extend(cur_sent)
sent_ids.extend([sent_id] * len(cur_sent))
sent_id = not sent_id
tf.logging.info("Finish with line %d", line_cnt)
if line_cnt == 0:
continue
input_data = np.array(input_data, dtype=np.int64)
sent_ids = np.array(sent_ids, dtype=np.bool)
total_line_cnt += line_cnt
input_shards.append((input_data, sent_ids))
tf.logging.info("[Task %d] Total number line: %d", idx, total_line_cnt)
tfrecord_dir = os.path.join(FLAGS.save_dir, "tfrecords")
filenames, num_batch = [], 0
# Randomly shuffle input shards (with a fixed but distinct random seed)
np.random.seed(100 * FLAGS.task + FLAGS.pass_id)
perm_indices = np.random.permutation(len(input_shards))
tf.logging.info("Using perm indices %s for pass %d",
perm_indices.tolist(), FLAGS.pass_id)
input_data_list, sent_ids_list = [], []
prev_sent_id = None
for perm_idx in perm_indices:
input_data, sent_ids = input_shards[perm_idx]
# make sure the `send_ids[0] == not prev_sent_id`
if prev_sent_id is not None and sent_ids[0] == prev_sent_id:
sent_ids = np.logical_not(sent_ids)
# append to temporary list
input_data_list.append(input_data)
sent_ids_list.append(sent_ids)
# update `prev_sent_id`
prev_sent_id = sent_ids[-1]
input_data = np.concatenate(input_data_list)
sent_ids = np.concatenate(sent_ids_list)
file_name, cur_num_batch = create_tfrecords(
save_dir=tfrecord_dir,
basename="{}-{}-{}".format(FLAGS.split, idx, FLAGS.pass_id),
data=[input_data, sent_ids],
bsz_per_host=FLAGS.bsz_per_host,
seq_len=FLAGS.seq_len,
bi_data=FLAGS.bi_data,
sp=sp,
)
filenames.append(file_name)
num_batch += cur_num_batch
record_info = {
"filenames": filenames,
"num_batch": num_batch
}
return record_info
def create_data(_):
# Validate FLAGS
assert FLAGS.bsz_per_host % FLAGS.num_core_per_host == 0
if not FLAGS.use_tpu:
FLAGS.num_core_per_host = 1 # forced to be one
# Make workdirs
if not tf.gfile.Exists(FLAGS.save_dir):
tf.gfile.MakeDirs(FLAGS.save_dir)
tfrecord_dir = os.path.join(FLAGS.save_dir, "tfrecords")
if not tf.gfile.Exists(tfrecord_dir):
tf.gfile.MakeDirs(tfrecord_dir)
# Create and dump corpus_info from task 0
if FLAGS.task == 0:
corpus_info = {
"vocab_size": VOCAB_SIZE,
"bsz_per_host": FLAGS.bsz_per_host,
"num_core_per_host": FLAGS.num_core_per_host,
"seq_len": FLAGS.seq_len,
"reuse_len": FLAGS.reuse_len,
"uncased": FLAGS.uncased,
"bi_data": FLAGS.bi_data,
"mask_alpha": FLAGS.mask_alpha,
"mask_beta": FLAGS.mask_beta,
"num_predict": FLAGS.num_predict,
"use_eod": FLAGS.use_eod,
"sp_path": FLAGS.sp_path,
"input_glob": FLAGS.input_glob,
}
corpus_info_path = os.path.join(FLAGS.save_dir, "corpus_info.json")
with tf.gfile.Open(corpus_info_path, "w") as fp:
json.dump(corpus_info, fp)
# Interleavely split the work into FLAGS.num_task splits
file_paths = sorted(tf.gfile.Glob(FLAGS.input_glob))
tf.logging.info("Use glob: %s", FLAGS.input_glob)
tf.logging.info("Find %d files: %s", len(file_paths), file_paths)
task_file_paths = file_paths[FLAGS.task::FLAGS.num_task]
if not task_file_paths:
tf.logging.info("Exit: task %d has no file to process.", FLAGS.task)
return
tf.logging.info("Task %d process %d files: %s",
FLAGS.task, len(task_file_paths), task_file_paths)
record_info = _create_data(FLAGS.task, task_file_paths)
record_prefix = "record_info-{}-{}-{}".format(
FLAGS.split, FLAGS.task, FLAGS.pass_id)
record_name = format_filename(
prefix=record_prefix,
bsz_per_host=FLAGS.bsz_per_host,
seq_len=FLAGS.seq_len,
mask_alpha=FLAGS.mask_alpha,
mask_beta=FLAGS.mask_beta,
reuse_len=FLAGS.reuse_len,
bi_data=FLAGS.bi_data,
suffix="json",
uncased=FLAGS.uncased,
fixed_num_predict=FLAGS.num_predict)
record_info_path = os.path.join(tfrecord_dir, record_name)
with tf.gfile.Open(record_info_path, "w") as fp:
json.dump(record_info, fp)
def batchify(data, bsz_per_host, sent_ids=None):
num_step = len(data) // bsz_per_host
data = data[:bsz_per_host * num_step]
data = data.reshape(bsz_per_host, num_step)
if sent_ids is not None:
sent_ids = sent_ids[:bsz_per_host * num_step]
sent_ids = sent_ids.reshape(bsz_per_host, num_step)
if sent_ids is not None:
return data, sent_ids
return data
def _split_a_and_b(data, sent_ids, begin_idx, tot_len, extend_target=False):
"""Split two segments from `data` starting from the index `begin_idx`."""
data_len = data.shape[0]
if begin_idx + tot_len >= data_len:
tf.logging.info("[_split_a_and_b] returns None: "
"begin_idx %d + tot_len %d >= data_len %d",
begin_idx, tot_len, data_len)
return None
end_idx = begin_idx + 1
cut_points = []
while end_idx < data_len:
if sent_ids[end_idx] != sent_ids[end_idx - 1]:
if end_idx - begin_idx >= tot_len: break
cut_points.append(end_idx)
end_idx += 1
a_begin = begin_idx
if len(cut_points) == 0 or random.random() < 0.5:
label = 0
if len(cut_points) == 0:
a_end = end_idx
else:
a_end = random.choice(cut_points)
b_len = max(1, tot_len - (a_end - a_begin))
# (zihang): `data_len - 1` to account for extend_target
b_begin = random.randint(0, data_len - 1 - b_len)
b_end = b_begin + b_len
while b_begin > 0 and sent_ids[b_begin - 1] == sent_ids[b_begin]:
b_begin -= 1
# (zihang): `data_len - 1` to account for extend_target
while b_end < data_len - 1 and sent_ids[b_end - 1] == sent_ids[b_end]:
b_end += 1
new_begin = a_end
else:
label = 1
a_end = random.choice(cut_points)
b_begin = a_end
b_end = end_idx
new_begin = b_end
while a_end - a_begin + b_end - b_begin > tot_len:
if a_end - a_begin > b_end - b_begin:
# delete the right side only for the LM objective
a_end -= 1
else:
b_end -= 1
ret = [data[a_begin: a_end], data[b_begin: b_end], label, new_begin]
if extend_target:
if a_end >= data_len or b_end >= data_len:
tf.logging.info("[_split_a_and_b] returns None: "
"a_end %d or b_end %d >= data_len %d",
a_end, b_end, data_len)
return None
a_target = data[a_begin + 1: a_end + 1]
b_target = data[b_begin: b_end + 1]
ret.extend([a_target, b_target])
return ret
def _is_start_piece(piece):
special_pieces = set(list('!"#$%&\"()*+,-./:;?@[\\]^_`{|}~'))
if (piece.startswith("▁") or piece.startswith("<")
or piece in special_pieces):
return True
else:
return False
def _sample_mask(sp, seg, reverse=False, max_gram=5, goal_num_predict=None):
"""Sample `goal_num_predict` tokens for partial prediction.
About `mask_beta` tokens are chosen in a context of `mask_alpha` tokens."""
seg_len = len(seg)
mask = np.array([False] * seg_len, dtype=np.bool)
num_predict = 0
ngrams = np.arange(1, max_gram + 1, dtype=np.int64)
pvals = 1. / np.arange(1, max_gram + 1)
pvals /= pvals.sum(keepdims=True)
if reverse:
seg = np.flip(seg, 0)
cur_len = 0
while cur_len < seg_len:
if goal_num_predict is not None and num_predict >= goal_num_predict: break
n = np.random.choice(ngrams, p=pvals)
if goal_num_predict is not None:
n = min(n, goal_num_predict - num_predict)
ctx_size = (n * FLAGS.mask_alpha) // FLAGS.mask_beta
l_ctx = np.random.choice(ctx_size)
r_ctx = ctx_size - l_ctx
# Find the start position of a complete token
beg = cur_len + l_ctx
while beg < seg_len and not _is_start_piece(sp.IdToPiece(seg[beg].item())):
beg += 1
if beg >= seg_len:
break
# Find the end position of the n-gram (start pos of the n+1-th gram)
end = beg + 1
cnt_ngram = 1
while end < seg_len:
if _is_start_piece(sp.IdToPiece(seg[beg].item())):
cnt_ngram += 1
if cnt_ngram > n:
break
end += 1
if end >= seg_len:
break
# Update
mask[beg:end] = True
num_predict += end - beg
cur_len = end + r_ctx
while goal_num_predict is not None and num_predict < goal_num_predict:
i = np.random.randint(seg_len)
if not mask[i]:
mask[i] = True
num_predict += 1
if reverse:
mask = np.flip(mask, 0)
return mask
def create_tfrecords(save_dir, basename, data, bsz_per_host, seq_len,
bi_data, sp):
data, sent_ids = data[0], data[1]
num_core = FLAGS.num_core_per_host
bsz_per_core = bsz_per_host // num_core
if bi_data:
assert bsz_per_host % (2 * FLAGS.num_core_per_host) == 0
fwd_data, fwd_sent_ids = batchify(data, bsz_per_host // 2, sent_ids)
fwd_data = fwd_data.reshape(num_core, 1, bsz_per_core // 2, -1)
fwd_sent_ids = fwd_sent_ids.reshape(num_core, 1, bsz_per_core // 2, -1)
bwd_data = fwd_data[:, :, :, ::-1]
bwd_sent_ids = fwd_sent_ids[:, :, :, ::-1]
data = np.concatenate(
[fwd_data, bwd_data], 1).reshape(bsz_per_host, -1)
sent_ids = np.concatenate(
[fwd_sent_ids, bwd_sent_ids], 1).reshape(bsz_per_host, -1)
else:
data, sent_ids = batchify(data, bsz_per_host, sent_ids)
tf.logging.info("Raw data shape %s.", data.shape)
file_name = format_filename(
prefix=basename,
bsz_per_host=bsz_per_host,
seq_len=seq_len,
bi_data=bi_data,
suffix="tfrecords",
mask_alpha=FLAGS.mask_alpha,
mask_beta=FLAGS.mask_beta,
reuse_len=FLAGS.reuse_len,
uncased=FLAGS.uncased,
fixed_num_predict=FLAGS.num_predict
)
save_path = os.path.join(save_dir, file_name)
record_writer = tf.python_io.TFRecordWriter(save_path)
tf.logging.info("Start writing %s.", save_path)
num_batch = 0
reuse_len = FLAGS.reuse_len
# [sep] x 2 + [cls]
assert reuse_len < seq_len - 3
data_len = data.shape[1]
sep_array = np.array([SEP_ID], dtype=np.int64)
cls_array = np.array([CLS_ID], dtype=np.int64)
i = 0
while i + seq_len <= data_len:
if num_batch % 500 == 0:
tf.logging.info("Processing batch %d", num_batch)
all_ok = True
features = []
for idx in range(bsz_per_host):
inp = data[idx, i: i + reuse_len]
tgt = data[idx, i + 1: i + reuse_len + 1]
results = _split_a_and_b(
data[idx],
sent_ids[idx],
begin_idx=i + reuse_len,
tot_len=seq_len - reuse_len - 3,
extend_target=True)
if results is None:
tf.logging.info("Break out with seq idx %d", i)
all_ok = False
break
# unpack the results
(a_data, b_data, label, _, a_target, b_target) = tuple(results)
# sample ngram spans to predict
reverse = bi_data and (idx // (bsz_per_core // 2)) % 2 == 1
if FLAGS.num_predict is None:
num_predict_0 = num_predict_1 = None
else:
num_predict_1 = FLAGS.num_predict // 2
num_predict_0 = FLAGS.num_predict - num_predict_1
mask_0 = _sample_mask(sp, inp, reverse=reverse,
goal_num_predict=num_predict_0)
mask_1 = _sample_mask(sp, np.concatenate([a_data, sep_array, b_data,
sep_array, cls_array]),
reverse=reverse, goal_num_predict=num_predict_1)
# concatenate data
cat_data = np.concatenate([inp, a_data, sep_array, b_data,
sep_array, cls_array])
seg_id = ([0] * (reuse_len + a_data.shape[0]) + [0] +
[1] * b_data.shape[0] + [1] + [2])
assert cat_data.shape[0] == seq_len
assert mask_0.shape[0] == seq_len // 2
assert mask_1.shape[0] == seq_len // 2
# the last two CLS's are not used, just for padding purposes
tgt = np.concatenate([tgt, a_target, b_target, cls_array, cls_array])
assert tgt.shape[0] == seq_len
is_masked = np.concatenate([mask_0, mask_1], 0)
if FLAGS.num_predict is not None:
assert np.sum(is_masked) == FLAGS.num_predict
feature = {
"input": _int64_feature(cat_data),
"is_masked": _int64_feature(is_masked),
"target": _int64_feature(tgt),
"seg_id": _int64_feature(seg_id),
"label": _int64_feature([label]),
}
features.append(feature)
if all_ok:
assert len(features) == bsz_per_host
for feature in features:
example = tf.train.Example(features=tf.train.Features(feature=feature))
record_writer.write(example.SerializeToString())
num_batch += 1
else:
break
i += reuse_len
record_writer.close()
tf.logging.info("Done writing %s. Num of batches: %d", save_path, num_batch)
return save_path, num_batch
################
# get_input_fn #
################
def _convert_example(example, use_bfloat16):
"""Cast int64 into int32 and float32 to bfloat16 if use_bfloat16."""
for key in list(example.keys()):
val = example[key]
if tf.keras.backend.is_sparse(val):
val = tf.sparse.to_dense(val)
if val.dtype == tf.int64:
val = tf.cast(val, tf.int32)
if use_bfloat16 and val.dtype == tf.float32:
val = tf.cast(val, tf.bfloat16)
example[key] = val
def parse_files_to_dataset(parser, file_names, split, num_batch, num_hosts,
host_id, num_core_per_host, bsz_per_core):
# list of file pathes
num_files = len(file_names)
num_files_per_host = num_files // num_hosts
my_start_file_id = host_id * num_files_per_host
my_end_file_id = (host_id + 1) * num_files_per_host
if host_id == num_hosts - 1:
my_end_file_id = num_files
file_paths = file_names[my_start_file_id: my_end_file_id]
tf.logging.info("Host %d handles %d files", host_id, len(file_paths))
assert split == "train"
dataset = tf.data.Dataset.from_tensor_slices(file_paths)
# file-level shuffle
if len(file_paths) > 1:
dataset = dataset.shuffle(len(file_paths))
# Note: we cannot perform sample-level shuffle here because this will violate
# the consecutive requirement of data stream.
dataset = tf.data.TFRecordDataset(dataset)
# (zihang): since we are doing online preprocessing, the parsed result of
# the same input at each time will be different. Thus, cache processed data
# is not helpful. It will use a lot of memory and lead to contrainer OOM.
# So, change to cache non-parsed raw data instead.
dataset = dataset.cache().map(parser,num_parallel_calls=tf.data.experimental.AUTOTUNE).repeat()
dataset = dataset.batch(bsz_per_core, drop_remainder=True)
dataset = dataset.prefetch(num_core_per_host * bsz_per_core)
return dataset
def _local_perm(inputs, targets, is_masked, perm_size, seq_len):
"""
Sample a permutation of the factorization order, and create an
attention mask accordingly.
Args:
inputs: int64 Tensor in shape [seq_len], input ids.
targets: int64 Tensor in shape [seq_len], target ids.
is_masked: bool Tensor in shape [seq_len]. True means being selected
for partial prediction.
perm_size: the length of longest permutation. Could be set to be reuse_len.
Should not be larger than reuse_len or there will be data leaks.
seq_len: int, sequence length.
"""
# Generate permutation indices
index = tf.range(seq_len, dtype=tf.int64)
index = tf.transpose(tf.reshape(index, [-1, perm_size]))
index = tf.random_shuffle(index)
index = tf.reshape(tf.transpose(index), [-1])
# `perm_mask` and `target_mask`
# non-functional tokens
non_func_tokens = tf.logical_not(tf.logical_or(
tf.equal(inputs, SEP_ID),
tf.equal(inputs, CLS_ID)))
non_mask_tokens = tf.logical_and(tf.logical_not(is_masked), non_func_tokens)
masked_or_func_tokens = tf.logical_not(non_mask_tokens)
# Set the permutation indices of non-masked (& non-funcional) tokens to the
# smallest index (-1):
# (1) they can be seen by all other positions
# (2) they cannot see masked positions, so there won"t be information leak
smallest_index = -tf.ones([seq_len], dtype=tf.int64)
rev_index = tf.where(non_mask_tokens, smallest_index, index)
# Create `target_mask`: non-funcional and maksed tokens
# 1: use mask as input and have loss
# 0: use token (or [SEP], [CLS]) as input and do not have loss
target_tokens = tf.logical_and(masked_or_func_tokens, non_func_tokens)
target_mask = tf.cast(target_tokens, tf.float32)
# Create `perm_mask`
# `target_tokens` cannot see themselves
self_rev_index = tf.where(target_tokens, rev_index, rev_index + 1)
# 1: cannot attend if i <= j and j is not non-masked (masked_or_func_tokens)
# 0: can attend if i > j or j is non-masked
perm_mask = tf.logical_and(
self_rev_index[:, None] <= rev_index[None, :],
masked_or_func_tokens)
perm_mask = tf.cast(perm_mask, tf.float32)
# new target: [next token] for LM and [curr token] (self) for PLM
new_targets = tf.concat([inputs[0: 1], targets[: -1]],
axis=0)
# construct inputs_k
inputs_k = inputs
# construct inputs_q
inputs_q = target_mask
return perm_mask, new_targets, target_mask, inputs_k, inputs_q
def get_dataset(params, num_hosts, num_core_per_host, split, file_names,
num_batch, seq_len, reuse_len, perm_size, mask_alpha,
mask_beta, use_bfloat16=False, num_predict=None):
bsz_per_core = params["batch_size"]
if num_hosts > 1:
host_id = params["context"].current_host
else:
host_id = 0
#### Function used to parse tfrecord
def parser(record):
"""function used to parse tfrecord."""
record_spec = {
"input": tf.FixedLenFeature([seq_len], tf.int64),
"target": tf.FixedLenFeature([seq_len], tf.int64),
"seg_id": tf.FixedLenFeature([seq_len], tf.int64),
"label": tf.FixedLenFeature([1], tf.int64),
"is_masked": tf.FixedLenFeature([seq_len], tf.int64),
}
# retrieve serialized example
example = tf.parse_single_example(
serialized=record,
features=record_spec)
inputs = example.pop("input")
target = example.pop("target")
is_masked = tf.cast(example.pop("is_masked"), tf.bool)
non_reuse_len = seq_len - reuse_len
assert perm_size <= reuse_len and perm_size <= non_reuse_len
perm_mask_0, target_0, target_mask_0, input_k_0, input_q_0 = _local_perm(
inputs[:reuse_len],
target[:reuse_len],
is_masked[:reuse_len],
perm_size,
reuse_len)
perm_mask_1, target_1, target_mask_1, input_k_1, input_q_1 = _local_perm(
inputs[reuse_len:],
target[reuse_len:],
is_masked[reuse_len:],
perm_size,
non_reuse_len)
perm_mask_0 = tf.concat([perm_mask_0, tf.ones([reuse_len, non_reuse_len])],
axis=1)
perm_mask_1 = tf.concat([tf.zeros([non_reuse_len, reuse_len]), perm_mask_1],
axis=1)
perm_mask = tf.concat([perm_mask_0, perm_mask_1], axis=0)
target = tf.concat([target_0, target_1], axis=0)
target_mask = tf.concat([target_mask_0, target_mask_1], axis=0)
input_k = tf.concat([input_k_0, input_k_1], axis=0)
input_q = tf.concat([input_q_0, input_q_1], axis=0)
if num_predict is not None:
indices = tf.range(seq_len, dtype=tf.int64)
bool_target_mask = tf.cast(target_mask, tf.bool)
indices = tf.boolean_mask(indices, bool_target_mask)
##### extra padding due to CLS/SEP introduced after prepro
actual_num_predict = tf.shape(indices)[0]
pad_len = num_predict - actual_num_predict
##### target_mapping
target_mapping = tf.one_hot(indices, seq_len, dtype=tf.float32)
paddings = tf.zeros([pad_len, seq_len], dtype=target_mapping.dtype)
target_mapping = tf.concat([target_mapping, paddings], axis=0)
example["target_mapping"] = tf.reshape(target_mapping,
[num_predict, seq_len])
##### target
target = tf.boolean_mask(target, bool_target_mask)
paddings = tf.zeros([pad_len], dtype=target.dtype)
target = tf.concat([target, paddings], axis=0)
example["target"] = tf.reshape(target, [num_predict])
##### target mask
target_mask = tf.concat(
[tf.ones([actual_num_predict], dtype=tf.float32),
tf.zeros([pad_len], dtype=tf.float32)],
axis=0)
example["target_mask"] = tf.reshape(target_mask, [num_predict])
else:
example["target"] = tf.reshape(target, [seq_len])
example["target_mask"] = tf.reshape(target_mask, [seq_len])
# reshape back to fixed shape
example["perm_mask"] = tf.reshape(perm_mask, [seq_len, seq_len])
example["input_k"] = tf.reshape(input_k, [seq_len])
example["input_q"] = tf.reshape(input_q, [seq_len])
_convert_example(example, use_bfloat16)
for k, v in example.items():
tf.logging.info("%s: %s", k, v)
return example
# Get dataset
dataset = parse_files_to_dataset(
parser=parser,
file_names=file_names,
split=split,
num_batch=num_batch,
num_hosts=num_hosts,
host_id=host_id,
num_core_per_host=num_core_per_host,
bsz_per_core=bsz_per_core)
return dataset
def get_input_fn(
tfrecord_dir,
split,
bsz_per_host,
seq_len,
reuse_len,
bi_data,
num_hosts=1,
num_core_per_host=1,
perm_size=None,
mask_alpha=None,
mask_beta=None,
uncased=False,
num_passes=None,
use_bfloat16=False,
num_predict=None):
# Merge all record infos into a single one
record_glob_base = format_filename(
prefix="record_info-{}-*".format(split),
bsz_per_host=bsz_per_host,
seq_len=seq_len,
bi_data=bi_data,
suffix="json",
mask_alpha=mask_alpha,
mask_beta=mask_beta,
reuse_len=reuse_len,
uncased=uncased,
fixed_num_predict=num_predict)
record_info = {"num_batch": 0, "filenames": []}
tfrecord_dirs = tfrecord_dir.split(",")
tf.logging.info("Use the following tfrecord dirs: %s", tfrecord_dirs)
for idx, record_dir in enumerate(tfrecord_dirs):
record_glob = os.path.join(record_dir, record_glob_base)
tf.logging.info("[%d] Record glob: %s", idx, record_glob)
record_paths = sorted(tf.gfile.Glob(record_glob))
tf.logging.info("[%d] Num of record info path: %d",
idx, len(record_paths))
cur_record_info = {"num_batch": 0, "filenames": []}
for record_info_path in record_paths:
if num_passes is not None:
record_info_name = os.path.basename(record_info_path)
fields = record_info_name.split(".")[0].split("-")
pass_id = int(fields[-1])
if len(fields) == 5 and pass_id >= num_passes:
tf.logging.info("Skip pass %d: %s", pass_id, record_info_name)
continue
with tf.gfile.Open(record_info_path, "r") as fp:
info = json.load(fp)
if num_passes is not None:
eff_num_passes = min(num_passes, len(info["filenames"]))
ratio = eff_num_passes / len(info["filenames"])
cur_record_info["num_batch"] += int(info["num_batch"] * ratio)
cur_record_info["filenames"] += info["filenames"][:eff_num_passes]
else:
cur_record_info["num_batch"] += info["num_batch"]
cur_record_info["filenames"] += info["filenames"]
# overwrite directory for `cur_record_info`
new_filenames = []
for filename in cur_record_info["filenames"]:
basename = os.path.basename(filename)
new_filename = os.path.join(record_dir, basename)
new_filenames.append(new_filename)
cur_record_info["filenames"] = new_filenames
tf.logging.info("[Dir %d] Number of chosen batches: %s",
idx, cur_record_info["num_batch"])
tf.logging.info("[Dir %d] Number of chosen files: %s",
idx, len(cur_record_info["filenames"]))
tf.logging.info(cur_record_info["filenames"])
# add `cur_record_info` to global `record_info`
record_info["num_batch"] += cur_record_info["num_batch"]
record_info["filenames"] += cur_record_info["filenames"]
tf.logging.info("Total number of batches: %d",
record_info["num_batch"])
tf.logging.info("Total number of files: %d",
len(record_info["filenames"]))
tf.logging.info(record_info["filenames"])
def input_fn(params):
"""docs."""
assert params["batch_size"] * num_core_per_host == bsz_per_host
dataset = get_dataset(
params=params,
num_hosts=num_hosts,
num_core_per_host=num_core_per_host,
split=split,
file_names=record_info["filenames"],
num_batch=record_info["num_batch"],
seq_len=seq_len,
reuse_len=reuse_len,
perm_size=perm_size,
mask_alpha=mask_alpha,
mask_beta=mask_beta,
use_bfloat16=use_bfloat16,
num_predict=num_predict)
return dataset
return input_fn, record_info
if __name__ == "__main__":
FLAGS = flags.FLAGS
flags.DEFINE_bool("use_tpu", True, help="whether to use TPUs")
flags.DEFINE_integer("bsz_per_host", 32, help="batch size per host.")
flags.DEFINE_integer("num_core_per_host", 8, help="num TPU cores per host.")
flags.DEFINE_integer("seq_len", 512,
help="Sequence length.")
flags.DEFINE_integer("reuse_len", 256,
help="Number of token that can be reused as memory. "
"Could be half of `seq_len`.")
flags.DEFINE_bool("uncased", True, help="Use uncased inputs or not.")
flags.DEFINE_bool("bi_data", True,
help="whether to create bidirectional data")
flags.DEFINE_integer("mask_alpha", default=6,
help="How many tokens to form a group.")
flags.DEFINE_integer("mask_beta", default=1,
help="How many tokens to mask within each group.")
flags.DEFINE_bool("use_eod", True,
help="whether to append EOD at the end of a doc.")
flags.DEFINE_bool("from_raw_text", True,
help="Whether the input is raw text or encoded ids.")
flags.DEFINE_integer("num_predict", default=85,
help="Num of tokens to predict.")
flags.DEFINE_string("input_glob", "data/example/*.txt",
help="Input file glob.")
flags.DEFINE_string("sp_path", "", help="Path to the sentence piece model.")
flags.DEFINE_string("save_dir", "proc_data/example",
help="Directory for saving the processed data.")
flags.DEFINE_enum("split", "train", ["train", "dev", "test"],
help="Save the data as which split.")
flags.DEFINE_integer("pass_id", 0, help="ID of the current pass."
"Different passes sample different negative segment.")
flags.DEFINE_integer("num_task", 1, help="Number of total tasks.")
flags.DEFINE_integer("task", 0, help="The Task ID. This value is used when "
"using multiple workers to identify each worker.")
tf.logging.set_verbosity(tf.logging.INFO)
tf.app.run(create_data)
| 29,915 | 31.659389 | 97 | py |
CLUE | CLUE-master/baselines/models/xlnet/run_cmrc_drcd.py | # coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import flags
import absl.logging as _logging # pylint: disable=unused-import
import collections
import os
import time
import math
import json
import six
import random
import gc
import numpy as np
if six.PY2:
import cPickle as pickle
else:
import pickle
import tensorflow as tf
import sentencepiece as spm
from prepro_utils import preprocess_text, encode_ids, encode_pieces, printable_text
import function_builder
import model_utils
import squad_utils
from data_utils import SEP_ID, CLS_ID, VOCAB_SIZE
SPIECE_UNDERLINE = u'▁'
SEG_ID_P = 0
SEG_ID_Q = 1
SEG_ID_CLS = 2
SEG_ID_PAD = 3
# Preprocessing
flags.DEFINE_bool("do_prepro", default=False,
help="Perform preprocessing only.")
flags.DEFINE_integer("num_proc", default=1,
help="Number of preprocessing processes.")
flags.DEFINE_integer("proc_id", default=0,
help="Process id for preprocessing.")
# Model
flags.DEFINE_string("model_config_path", default=None,
help="Model config path.")
flags.DEFINE_float("dropout", default=0.1,
help="Dropout rate.")
flags.DEFINE_float("dropatt", default=0.1,
help="Attention dropout rate.")
flags.DEFINE_integer("clamp_len", default=-1,
help="Clamp length.")
flags.DEFINE_string("summary_type", default="last",
help="Method used to summarize a sequence into a vector.")
flags.DEFINE_bool("use_bfloat16", default=False,
help="Whether to use bfloat16.")
# Parameter initialization
flags.DEFINE_enum("init", default="normal",
enum_values=["normal", "uniform"],
help="Initialization method.")
flags.DEFINE_float("init_std", default=0.02,
help="Initialization std when init is normal.")
flags.DEFINE_float("init_range", default=0.1,
help="Initialization std when init is uniform.")
# I/O paths
flags.DEFINE_bool("overwrite_data", default=False,
help="If False, will use cached data if available.")
flags.DEFINE_string("init_checkpoint", default=None,
help="checkpoint path for initializing the model. "
"Could be a pretrained model or a finetuned model.")
flags.DEFINE_bool("init_global_vars", default=False,
help="If true, init all global vars. If false, init "
"trainable vars only.")
flags.DEFINE_string("output_dir", default="",
help="Output dir for TF records.")
flags.DEFINE_string("predict_dir", default="",
help="Dir for predictions.")
flags.DEFINE_string("spiece_model_file", default="",
help="Sentence Piece model path.")
flags.DEFINE_string("model_dir", default="",
help="Directory for saving the finetuned model.")
flags.DEFINE_string("train_file", default="",
help="Path of train file.")
flags.DEFINE_string("predict_file", default="",
help="Path of prediction file.")
# Data preprocessing config
flags.DEFINE_integer("max_seq_length",
default=512, help="Max sequence length")
flags.DEFINE_integer("max_query_length",
default=64, help="Max query length")
flags.DEFINE_integer("doc_stride",
default=128, help="Doc stride")
flags.DEFINE_integer("max_answer_length",
default=64, help="Max answer length")
flags.DEFINE_bool("uncased", default=False, help="Use uncased data.")
# TPUs and machines
flags.DEFINE_bool("use_tpu", default=False, help="whether to use TPU.")
flags.DEFINE_integer("num_hosts", default=1, help="How many TPU hosts.")
flags.DEFINE_integer("num_core_per_host", default=8,
help="8 for TPU v2 and v3-8, 16 for larger TPU v3 pod. In the context "
"of GPU training, it refers to the number of GPUs used.")
flags.DEFINE_string("tpu_job_name", default=None, help="TPU worker job name.")
flags.DEFINE_string("tpu", default=None, help="TPU name.")
flags.DEFINE_string("tpu_zone", default=None, help="TPU zone.")
flags.DEFINE_string("gcp_project", default=None, help="gcp project.")
flags.DEFINE_string("master", default=None, help="master")
flags.DEFINE_integer("iterations", default=1000,
help="number of iterations per TPU training loop.")
# Training
flags.DEFINE_bool("do_train", default=True, help="whether to do training")
flags.DEFINE_integer("train_batch_size", default=48,
help="batch size for training")
flags.DEFINE_integer("train_steps", default=8000,
help="Number of training steps")
flags.DEFINE_integer("warmup_steps", default=0, help="number of warmup steps")
flags.DEFINE_integer("save_steps", default=None,
help="Save the model for every save_steps. "
"If None, not to save any model.")
flags.DEFINE_integer("max_save", default=5,
help="Max number of checkpoints to save. "
"Use 0 to save all.")
flags.DEFINE_integer("shuffle_buffer", default=2048,
help="Buffer size used for shuffle.")
# Optimization
flags.DEFINE_float("learning_rate", default=3e-5, help="initial learning rate")
flags.DEFINE_float("min_lr_ratio", default=0.0,
help="min lr ratio for cos decay.")
flags.DEFINE_float("clip", default=1.0, help="Gradient clipping")
flags.DEFINE_float("weight_decay", default=0.00, help="Weight decay rate")
flags.DEFINE_float("adam_epsilon", default=1e-6, help="Adam epsilon")
flags.DEFINE_string("decay_method", default="poly", help="poly or cos")
flags.DEFINE_float("lr_layer_decay_rate", default=0.75,
help="Top layer: lr[L] = FLAGS.learning_rate."
"Lower layers: lr[l-1] = lr[l] * lr_layer_decay_rate.")
# Eval / Prediction
flags.DEFINE_bool("do_predict", default=False, help="whether to do predict")
flags.DEFINE_integer("predict_batch_size", default=32,
help="batch size for prediction")
flags.DEFINE_integer("n_best_size", default=5,
help="n best size for predictions")
flags.DEFINE_integer("start_n_top", default=5, help="Beam size for span start.")
flags.DEFINE_integer("end_n_top", default=5, help="Beam size for span end.")
flags.DEFINE_string("target_eval_key", default="best_f1",
help="Use has_ans_f1 for Model I.")
FLAGS = flags.FLAGS
class SquadExample(object):
"""A single training/test example for simple sequence classification.
For examples without an answer, the start and end position are -1.
"""
def __init__(self,
qas_id,
question_text,
paragraph_text,
orig_answer_text=None,
start_position=None,
is_impossible=False):
self.qas_id = qas_id
self.question_text = question_text
self.paragraph_text = paragraph_text
self.orig_answer_text = orig_answer_text
self.start_position = start_position
self.is_impossible = is_impossible
def __str__(self):
return self.__repr__()
def __repr__(self):
s = ""
s += "qas_id: %s" % (printable_text(self.qas_id))
s += ", question_text: %s" % (
printable_text(self.question_text))
s += ", paragraph_text: [%s]" % (" ".join(self.paragraph_text))
if self.start_position:
s += ", start_position: %d" % (self.start_position)
if self.start_position:
s += ", is_impossible: %r" % (self.is_impossible)
return s
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
unique_id,
example_index,
doc_span_index,
tok_start_to_orig_index,
tok_end_to_orig_index,
token_is_max_context,
input_ids,
input_mask,
p_mask,
segment_ids,
paragraph_len,
cls_index,
start_position=None,
end_position=None,
is_impossible=None):
self.unique_id = unique_id
self.example_index = example_index
self.doc_span_index = doc_span_index
self.tok_start_to_orig_index = tok_start_to_orig_index
self.tok_end_to_orig_index = tok_end_to_orig_index
self.token_is_max_context = token_is_max_context
self.input_ids = input_ids
self.input_mask = input_mask
self.p_mask = p_mask
self.segment_ids = segment_ids
self.paragraph_len = paragraph_len
self.cls_index = cls_index
self.start_position = start_position
self.end_position = end_position
self.is_impossible = is_impossible
def read_squad_examples(input_file, is_training):
"""Read a SQuAD json file into a list of SquadExample."""
with tf.gfile.Open(input_file, "r") as reader:
input_data = json.load(reader)["data"]
examples = []
for entry in input_data:
for paragraph in entry["paragraphs"]:
paragraph_text = paragraph["context"]
for qa in paragraph["qas"]:
qas_id = qa["id"]
question_text = qa["question"]
start_position = None
orig_answer_text = None
is_impossible = False
if is_training:
if "is_impossible" in qa:
is_impossible = qa["is_impossible"]
else:
is_impossible = False
if (len(qa["answers"]) != 1) and (not is_impossible):
raise ValueError(
"For training, each question should have exactly 1 answer.")
if not is_impossible:
answer = qa["answers"][0]
orig_answer_text = answer["text"]
start_position = answer["answer_start"]
else:
start_position = -1
orig_answer_text = ""
example = SquadExample(
qas_id=qas_id,
question_text=question_text,
paragraph_text=paragraph_text,
orig_answer_text=orig_answer_text,
start_position=start_position,
is_impossible=is_impossible)
examples.append(example)
return examples
def _convert_index(index, pos, M=None, is_start=True):
if pos >= len(index):
pos = len(index) - 1
if index[pos] is not None:
return index[pos]
N = len(index)
rear = pos
while rear < N - 1 and index[rear] is None:
rear += 1
front = pos
while front > 0 and index[front] is None:
front -= 1
assert index[front] is not None or index[rear] is not None
if index[front] is None:
if index[rear] >= 1:
if is_start:
return 0
else:
return index[rear] - 1
return index[rear]
if index[rear] is None:
if M is not None and index[front] < M - 1:
if is_start:
return index[front] + 1
else:
return M - 1
return index[front]
if is_start:
if index[rear] > index[front] + 1:
return index[front] + 1
else:
return index[rear]
else:
if index[rear] > index[front] + 1:
return index[rear] - 1
else:
return index[front]
def convert_examples_to_features(examples, sp_model, max_seq_length,
doc_stride, max_query_length, is_training,
output_fn):
"""Loads a data file into a list of `InputBatch`s."""
cnt_pos, cnt_neg = 0, 0
unique_id = 1000000000
max_N, max_M = 1024, 1024
f = np.zeros((max_N, max_M), dtype=np.float32)
for (example_index, example) in enumerate(examples):
if example_index % 100 == 0:
tf.logging.info('Converting {}/{} pos {} neg {}'.format(
example_index, len(examples), cnt_pos, cnt_neg))
query_tokens = encode_ids(
sp_model,
preprocess_text(example.question_text, lower=FLAGS.uncased))
if len(query_tokens) > max_query_length:
query_tokens = query_tokens[0:max_query_length]
paragraph_text = example.paragraph_text
para_tokens = encode_pieces(
sp_model,
preprocess_text(example.paragraph_text, lower=FLAGS.uncased))
chartok_to_tok_index = []
tok_start_to_chartok_index = []
tok_end_to_chartok_index = []
char_cnt = 0
for i, token in enumerate(para_tokens):
chartok_to_tok_index.extend([i] * len(token))
tok_start_to_chartok_index.append(char_cnt)
char_cnt += len(token)
tok_end_to_chartok_index.append(char_cnt - 1)
tok_cat_text = ''.join(para_tokens).replace(SPIECE_UNDERLINE, ' ')
N, M = len(paragraph_text), len(tok_cat_text)
if N > max_N or M > max_M:
max_N = max(N, max_N)
max_M = max(M, max_M)
f = np.zeros((max_N, max_M), dtype=np.float32)
gc.collect()
g = {}
def _lcs_match(max_dist):
f.fill(0)
g.clear()
### longest common sub sequence
# f[i, j] = max(f[i - 1, j], f[i, j - 1], f[i - 1, j - 1] + match(i, j))
for i in range(N):
# note(zhiliny):
# unlike standard LCS, this is specifically optimized for the setting
# because the mismatch between sentence pieces and original text will
# be small
for j in range(i - max_dist, i + max_dist):
if j >= M or j < 0: continue
if i > 0:
g[(i, j)] = 0
f[i, j] = f[i - 1, j]
if j > 0 and f[i, j - 1] > f[i, j]:
g[(i, j)] = 1
f[i, j] = f[i, j - 1]
f_prev = f[i - 1, j - 1] if i > 0 and j > 0 else 0
if (preprocess_text(paragraph_text[i], lower=FLAGS.uncased,
remove_space=False)
== tok_cat_text[j]
and f_prev + 1 > f[i, j]):
g[(i, j)] = 2
f[i, j] = f_prev + 1
max_dist = abs(N - M) + 5
for _ in range(2):
_lcs_match(max_dist)
if f[N - 1, M - 1] > 0.8 * N: break
max_dist *= 2
orig_to_chartok_index = [None] * N
chartok_to_orig_index = [None] * M
i, j = N - 1, M - 1
while i >= 0 and j >= 0:
if (i, j) not in g: break
if g[(i, j)] == 2:
orig_to_chartok_index[i] = j
chartok_to_orig_index[j] = i
i, j = i - 1, j - 1
elif g[(i, j)] == 1:
j = j - 1
else:
i = i - 1
if all(v is None for v in orig_to_chartok_index) or f[N - 1, M - 1] < 0.8 * N:
print('MISMATCH DETECTED!')
continue
tok_start_to_orig_index = []
tok_end_to_orig_index = []
for i in range(len(para_tokens)):
start_chartok_pos = tok_start_to_chartok_index[i]
end_chartok_pos = tok_end_to_chartok_index[i]
start_orig_pos = _convert_index(chartok_to_orig_index, start_chartok_pos,
N, is_start=True)
end_orig_pos = _convert_index(chartok_to_orig_index, end_chartok_pos,
N, is_start=False)
tok_start_to_orig_index.append(start_orig_pos)
tok_end_to_orig_index.append(end_orig_pos)
if not is_training:
tok_start_position = tok_end_position = None
if is_training and example.is_impossible:
tok_start_position = -1
tok_end_position = -1
if is_training and not example.is_impossible:
start_position = example.start_position
end_position = start_position + len(example.orig_answer_text) - 1
start_chartok_pos = _convert_index(orig_to_chartok_index, start_position,
is_start=True)
tok_start_position = chartok_to_tok_index[start_chartok_pos]
end_chartok_pos = _convert_index(orig_to_chartok_index, end_position,
is_start=False)
tok_end_position = chartok_to_tok_index[end_chartok_pos]
assert tok_start_position <= tok_end_position
def _piece_to_id(x):
if six.PY2 and isinstance(x, unicode):
x = x.encode('utf-8')
return sp_model.PieceToId(x)
all_doc_tokens = list(map(_piece_to_id, para_tokens))
# The -3 accounts for [CLS], [SEP] and [SEP]
max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
# We can have documents that are longer than the maximum sequence length.
# To deal with this we do a sliding window approach, where we take chunks
# of the up to our max length with a stride of `doc_stride`.
_DocSpan = collections.namedtuple( # pylint: disable=invalid-name
"DocSpan", ["start", "length"])
doc_spans = []
start_offset = 0
while start_offset < len(all_doc_tokens):
length = len(all_doc_tokens) - start_offset
if length > max_tokens_for_doc:
length = max_tokens_for_doc
doc_spans.append(_DocSpan(start=start_offset, length=length))
if start_offset + length == len(all_doc_tokens):
break
start_offset += min(length, doc_stride)
for (doc_span_index, doc_span) in enumerate(doc_spans):
tokens = []
token_is_max_context = {}
segment_ids = []
p_mask = []
cur_tok_start_to_orig_index = []
cur_tok_end_to_orig_index = []
for i in range(doc_span.length):
split_token_index = doc_span.start + i
cur_tok_start_to_orig_index.append(
tok_start_to_orig_index[split_token_index])
cur_tok_end_to_orig_index.append(
tok_end_to_orig_index[split_token_index])
is_max_context = _check_is_max_context(doc_spans, doc_span_index,
split_token_index)
token_is_max_context[len(tokens)] = is_max_context
tokens.append(all_doc_tokens[split_token_index])
segment_ids.append(SEG_ID_P)
p_mask.append(0)
paragraph_len = len(tokens)
tokens.append(SEP_ID)
segment_ids.append(SEG_ID_P)
p_mask.append(1)
# note(zhiliny): we put P before Q
# because during pretraining, B is always shorter than A
for token in query_tokens:
tokens.append(token)
segment_ids.append(SEG_ID_Q)
p_mask.append(1)
tokens.append(SEP_ID)
segment_ids.append(SEG_ID_Q)
p_mask.append(1)
cls_index = len(segment_ids)
tokens.append(CLS_ID)
segment_ids.append(SEG_ID_CLS)
p_mask.append(0)
input_ids = tokens
# The mask has 0 for real tokens and 1 for padding tokens. Only real
# tokens are attended to.
input_mask = [0] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(1)
segment_ids.append(SEG_ID_PAD)
p_mask.append(1)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
assert len(p_mask) == max_seq_length
span_is_impossible = example.is_impossible
start_position = None
end_position = None
if is_training and not span_is_impossible:
# For training, if our document chunk does not contain an annotation
# we throw it out, since there is nothing to predict.
doc_start = doc_span.start
doc_end = doc_span.start + doc_span.length - 1
out_of_span = False
if not (tok_start_position >= doc_start and
tok_end_position <= doc_end):
out_of_span = True
if out_of_span:
# continue
start_position = 0
end_position = 0
span_is_impossible = True
else:
# note(zhiliny): we put P before Q, so doc_offset should be zero.
# doc_offset = len(query_tokens) + 2
doc_offset = 0
start_position = tok_start_position - doc_start + doc_offset
end_position = tok_end_position - doc_start + doc_offset
if is_training and span_is_impossible:
start_position = cls_index
end_position = cls_index
if example_index < 20:
tf.logging.info("*** Example ***")
tf.logging.info("unique_id: %s" % (unique_id))
tf.logging.info("example_index: %s" % (example_index))
tf.logging.info("doc_span_index: %s" % (doc_span_index))
tf.logging.info("tok_start_to_orig_index: %s" % " ".join(
[str(x) for x in cur_tok_start_to_orig_index]))
tf.logging.info("tok_end_to_orig_index: %s" % " ".join(
[str(x) for x in cur_tok_end_to_orig_index]))
tf.logging.info("token_is_max_context: %s" % " ".join([
"%d:%s" % (x, y) for (x, y) in six.iteritems(token_is_max_context)
]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info(
"input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info(
"segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
if is_training and span_is_impossible:
tf.logging.info("impossible example span")
if is_training and not span_is_impossible:
pieces = [sp_model.IdToPiece(token) for token in
tokens[start_position: (end_position + 1)]]
answer_text = sp_model.DecodePieces(pieces)
tf.logging.info("start_position: %d" % (start_position))
tf.logging.info("end_position: %d" % (end_position))
tf.logging.info(
"answer: %s" % (printable_text(answer_text)))
# note(zhiliny): With multi processing,
# the example_index is actually the index within the current process
# therefore we use example_index=None to avoid being used in the future.
# The current code does not use example_index of training data.
if is_training:
feat_example_index = None
else:
feat_example_index = example_index
feature = InputFeatures(
unique_id=unique_id,
example_index=feat_example_index,
doc_span_index=doc_span_index,
tok_start_to_orig_index=cur_tok_start_to_orig_index,
tok_end_to_orig_index=cur_tok_end_to_orig_index,
token_is_max_context=token_is_max_context,
input_ids=input_ids,
input_mask=input_mask,
p_mask=p_mask,
segment_ids=segment_ids,
paragraph_len=paragraph_len,
cls_index=cls_index,
start_position=start_position,
end_position=end_position,
is_impossible=span_is_impossible)
# Run callback
output_fn(feature)
unique_id += 1
if span_is_impossible:
cnt_neg += 1
else:
cnt_pos += 1
tf.logging.info("Total number of instances: {} = pos {} neg {}".format(
cnt_pos + cnt_neg, cnt_pos, cnt_neg))
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a single
# token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a gallon of milk
# Span A: the man went to the
# Span B: to the store and bought
# Span C: and bought a gallon of
# ...
#
# Now the word 'bought' will have two scores from spans B and C. We only
# want to consider the score with "maximum context", which we define as
# the *minimum* of its left and right context (the *sum* of left and
# right context will always be the same, of course).
#
# In the example the maximum context for 'bought' would be span C since
# it has 1 left context and 3 right context, while span B has 4 left context
# and 0 right context.
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
class FeatureWriter(object):
"""Writes InputFeature to TF example file."""
def __init__(self, filename, is_training):
self.filename = filename
self.is_training = is_training
self.num_features = 0
self._writer = tf.python_io.TFRecordWriter(filename)
def process_feature(self, feature):
"""Write a InputFeature to the TFRecordWriter as a tf.train.Example."""
self.num_features += 1
def create_int_feature(values):
feature = tf.train.Feature(
int64_list=tf.train.Int64List(value=list(values)))
return feature
def create_float_feature(values):
f = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
return f
features = collections.OrderedDict()
features["unique_ids"] = create_int_feature([feature.unique_id])
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_float_feature(feature.input_mask)
features["p_mask"] = create_float_feature(feature.p_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["cls_index"] = create_int_feature([feature.cls_index])
if self.is_training:
features["start_positions"] = create_int_feature([feature.start_position])
features["end_positions"] = create_int_feature([feature.end_position])
impossible = 0
if feature.is_impossible:
impossible = 1
features["is_impossible"] = create_float_feature([impossible])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
self._writer.write(tf_example.SerializeToString())
def close(self):
self._writer.close()
RawResult = collections.namedtuple("RawResult",
["unique_id", "start_top_log_probs", "start_top_index",
"end_top_log_probs", "end_top_index"])
_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
"PrelimPrediction",
["feature_index", "start_index", "end_index",
"start_log_prob", "end_log_prob"])
_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
"NbestPrediction", ["text", "start_log_prob", "end_log_prob"])
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, output_prediction_file,
output_nbest_file,
orig_data):
"""Write final predictions to the json file and log-odds of null if needed."""
tf.logging.info("Writing predictions to: %s" % (output_prediction_file))
# tf.logging.info("Writing nbest to: %s" % (output_nbest_file))
example_index_to_features = collections.defaultdict(list)
for feature in all_features:
example_index_to_features[feature.example_index].append(feature)
unique_id_to_result = {}
for result in all_results:
unique_id_to_result[result.unique_id] = result
all_predictions = collections.OrderedDict()
all_nbest_json = collections.OrderedDict()
scores_diff_json = collections.OrderedDict()
for (example_index, example) in enumerate(all_examples):
features = example_index_to_features[example_index]
prelim_predictions = []
# keep track of the minimum score of null start+end of position 0
for (feature_index, feature) in enumerate(features):
result = unique_id_to_result[feature.unique_id]
for i in range(FLAGS.start_n_top):
for j in range(FLAGS.end_n_top):
start_log_prob = result.start_top_log_probs[i]
start_index = result.start_top_index[i]
j_index = i * FLAGS.end_n_top + j
end_log_prob = result.end_top_log_probs[j_index]
end_index = result.end_top_index[j_index]
# We could hypothetically create invalid predictions, e.g., predict
# that the start of the span is in the question. We throw out all
# invalid predictions.
if start_index >= feature.paragraph_len - 1:
continue
if end_index >= feature.paragraph_len - 1:
continue
if not feature.token_is_max_context.get(start_index, False):
continue
if end_index < start_index:
continue
length = end_index - start_index + 1
if length > max_answer_length:
continue
prelim_predictions.append(
_PrelimPrediction(
feature_index=feature_index,
start_index=start_index,
end_index=end_index,
start_log_prob=start_log_prob,
end_log_prob=end_log_prob))
prelim_predictions = sorted(
prelim_predictions,
key=lambda x: (x.start_log_prob + x.end_log_prob),
reverse=True)
seen_predictions = {}
nbest = []
for pred in prelim_predictions:
if len(nbest) >= n_best_size:
break
feature = features[pred.feature_index]
tok_start_to_orig_index = feature.tok_start_to_orig_index
tok_end_to_orig_index = feature.tok_end_to_orig_index
start_orig_pos = tok_start_to_orig_index[pred.start_index]
end_orig_pos = tok_end_to_orig_index[pred.end_index]
paragraph_text = example.paragraph_text
final_text = paragraph_text[start_orig_pos: end_orig_pos + 1].strip()
if final_text in seen_predictions:
continue
seen_predictions[final_text] = True
nbest.append(
_NbestPrediction(
text=final_text,
start_log_prob=pred.start_log_prob,
end_log_prob=pred.end_log_prob))
# In very rare edge cases we could have no valid predictions. So we
# just create a nonce prediction in this case to avoid failure.
if not nbest:
nbest.append(
_NbestPrediction(text="", start_log_prob=-1e6,
end_log_prob=-1e6))
total_scores = []
best_non_null_entry = None
for entry in nbest:
total_scores.append(entry.start_log_prob + entry.end_log_prob)
if not best_non_null_entry:
best_non_null_entry = entry
probs = _compute_softmax(total_scores)
nbest_json = []
for (i, entry) in enumerate(nbest):
output = collections.OrderedDict()
output["text"] = entry.text
output["probability"] = probs[i]
output["start_log_prob"] = entry.start_log_prob
output["end_log_prob"] = entry.end_log_prob
nbest_json.append(output)
assert len(nbest_json) >= 1
assert best_non_null_entry is not None
score_diff = 0 #score_null
scores_diff_json[example.qas_id] = score_diff
# note(zhiliny): always predict best_non_null_entry
# and the evaluation script will search for the best threshold
all_predictions[example.qas_id] = best_non_null_entry.text
all_nbest_json[example.qas_id] = nbest_json
with tf.gfile.GFile(output_prediction_file, "w") as writer:
writer.write(json.dumps(all_predictions, indent=4) + "\n")
with tf.gfile.GFile(output_nbest_file, "w") as writer:
writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
qid_to_has_ans = squad_utils.make_qid_to_has_ans(orig_data)
has_ans_qids = [k for k, v in qid_to_has_ans.items() if v]
no_ans_qids = [k for k, v in qid_to_has_ans.items() if not v]
exact_raw, f1_raw = squad_utils.get_raw_scores(orig_data, all_predictions)
out_eval = {}
squad_utils.find_all_best_thresh_v2(out_eval, all_predictions, exact_raw, f1_raw,
scores_diff_json, qid_to_has_ans)
return out_eval
def _get_best_indexes(logits, n_best_size):
"""Get the n-best logits from a list."""
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if i >= n_best_size:
break
best_indexes.append(index_and_score[i][0])
return best_indexes
def _compute_softmax(scores):
"""Compute softmax probability over raw logits."""
if not scores:
return []
max_score = None
for score in scores:
if max_score is None or score > max_score:
max_score = score
exp_scores = []
total_sum = 0.0
for score in scores:
x = math.exp(score - max_score)
exp_scores.append(x)
total_sum += x
probs = []
for score in exp_scores:
probs.append(score / total_sum)
return probs
def input_fn_builder(input_glob, seq_length, is_training, drop_remainder,
num_hosts, num_threads=8):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"unique_ids": tf.FixedLenFeature([], tf.int64),
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.float32),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"cls_index": tf.FixedLenFeature([], tf.int64),
"p_mask": tf.FixedLenFeature([seq_length], tf.float32)
}
if is_training:
name_to_features["start_positions"] = tf.FixedLenFeature([], tf.int64)
name_to_features["end_positions"] = tf.FixedLenFeature([], tf.int64)
name_to_features["is_impossible"] = tf.FixedLenFeature([], tf.float32)
tf.logging.info("Input tfrecord file glob {}".format(input_glob))
global_input_paths = tf.gfile.Glob(input_glob)
tf.logging.info("Find {} input paths {}".format(
len(global_input_paths), global_input_paths))
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.cast(t, tf.int32)
example[name] = t
return example
def input_fn(params):
"""The actual input function."""
if FLAGS.use_tpu:
batch_size = params["batch_size"]
elif is_training:
batch_size = FLAGS.train_batch_size
else:
batch_size = FLAGS.predict_batch_size
# Split tfrecords across hosts
if num_hosts > 1:
host_id = params["context"].current_host
num_files = len(global_input_paths)
if num_files >= num_hosts:
num_files_per_host = (num_files + num_hosts - 1) // num_hosts
my_start_file_id = host_id * num_files_per_host
my_end_file_id = min((host_id + 1) * num_files_per_host, num_files)
input_paths = global_input_paths[my_start_file_id: my_end_file_id]
tf.logging.info("Host {} handles {} files".format(host_id,
len(input_paths)))
else:
input_paths = global_input_paths
if len(input_paths) == 1:
d = tf.data.TFRecordDataset(input_paths[0])
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
if is_training:
d = d.shuffle(buffer_size=FLAGS.shuffle_buffer)
d = d.repeat()
else:
d = tf.data.Dataset.from_tensor_slices(input_paths)
# file level shuffle
d = d.shuffle(len(input_paths)).repeat()
# `cycle_length` is the number of parallel files that get read.
cycle_length = min(num_threads, len(input_paths))
d = d.apply(
tf.contrib.data.parallel_interleave(
tf.data.TFRecordDataset,
sloppy=is_training,
cycle_length=cycle_length))
if is_training:
# sample level shuffle
d = d.shuffle(buffer_size=FLAGS.shuffle_buffer)
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
num_parallel_batches=num_threads,
drop_remainder=drop_remainder))
d = d.prefetch(1024)
return d
return input_fn
def get_model_fn():
def model_fn(features, labels, mode, params):
#### Training or Evaluation
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
#### Get loss from inputs
outputs = function_builder.get_qa_outputs(FLAGS, features, is_training)
#### Check model parameters
num_params = sum([np.prod(v.shape) for v in tf.trainable_variables()])
tf.logging.info('#params: {}'.format(num_params))
scaffold_fn = None
#### Evaluation mode
if mode == tf.estimator.ModeKeys.PREDICT:
if FLAGS.init_checkpoint:
tf.logging.info("init_checkpoint not being used in predict mode.")
predictions = {
"unique_ids": features["unique_ids"],
"start_top_index": outputs["start_top_index"],
"start_top_log_probs": outputs["start_top_log_probs"],
"end_top_index": outputs["end_top_index"],
"end_top_log_probs": outputs["end_top_log_probs"]
}
if FLAGS.use_tpu:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
else:
output_spec = tf.estimator.EstimatorSpec(
mode=mode, predictions=predictions)
return output_spec
### Compute loss
seq_length = tf.shape(features["input_ids"])[1]
def compute_loss(log_probs, positions):
one_hot_positions = tf.one_hot(
positions, depth=seq_length, dtype=tf.float32)
loss = - tf.reduce_sum(one_hot_positions * log_probs, axis=-1)
loss = tf.reduce_mean(loss)
return loss
start_loss = compute_loss(
outputs["start_log_probs"], features["start_positions"])
end_loss = compute_loss(
outputs["end_log_probs"], features["end_positions"])
total_loss = (start_loss + end_loss) * 0.5
#### Configuring the optimizer
train_op, learning_rate, _ = model_utils.get_train_op(FLAGS, total_loss)
monitor_dict = {}
monitor_dict["lr"] = learning_rate
#### load pretrained models
scaffold_fn = model_utils.init_from_checkpoint(FLAGS)
#### Constucting training TPUEstimatorSpec with new cache.
if FLAGS.use_tpu:
host_call = function_builder.construct_scalar_host_call(
monitor_dict=monitor_dict,
model_dir=FLAGS.model_dir,
prefix="train/",
reduce_fn=tf.reduce_mean)
train_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, loss=total_loss, train_op=train_op, host_call=host_call,
scaffold_fn=scaffold_fn)
else:
train_spec = tf.estimator.EstimatorSpec(
mode=mode, loss=total_loss, train_op=train_op)
return train_spec
return model_fn
def _get_spm_basename():
spm_basename = os.path.basename(FLAGS.spiece_model_file)
return spm_basename
def preprocess():
sp_model = spm.SentencePieceProcessor()
sp_model.Load(FLAGS.spiece_model_file)
spm_basename = _get_spm_basename()
train_rec_file = os.path.join(
FLAGS.output_dir,
"{}.{}.slen-{}.qlen-{}.train.tf_record".format(
spm_basename, FLAGS.proc_id, FLAGS.max_seq_length,
FLAGS.max_query_length))
tf.logging.info("Read examples from {}".format(FLAGS.train_file))
train_examples = read_squad_examples(FLAGS.train_file, is_training=True)
train_examples = train_examples[FLAGS.proc_id::FLAGS.num_proc]
# Pre-shuffle the input to avoid having to make a very large shuffle
# buffer in the `input_fn`.
random.shuffle(train_examples)
tf.logging.info("Write to {}".format(train_rec_file))
train_writer = FeatureWriter(
filename=train_rec_file,
is_training=True)
convert_examples_to_features(
examples=train_examples,
sp_model=sp_model,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=True,
output_fn=train_writer.process_feature)
train_writer.close()
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
if not tf.gfile.Exists(FLAGS.output_dir):
tf.gfile.MakeDirs(FLAGS.output_dir)
if FLAGS.do_prepro:
preprocess()
return
#### Validate flags
if FLAGS.save_steps is not None:
FLAGS.iterations = min(FLAGS.iterations, FLAGS.save_steps)
if not FLAGS.do_train and not FLAGS.do_predict:
raise ValueError(
"At least one of `do_train` and `do_predict` must be True.")
if FLAGS.do_predict and not tf.gfile.Exists(FLAGS.predict_dir):
tf.gfile.MakeDirs(FLAGS.predict_dir)
sp_model = spm.SentencePieceProcessor()
sp_model.Load(FLAGS.spiece_model_file)
### TPU Configuration
run_config = model_utils.configure_tpu(FLAGS)
model_fn = get_model_fn()
spm_basename = _get_spm_basename()
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
if FLAGS.use_tpu:
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
else:
estimator = tf.estimator.Estimator(
model_fn=model_fn,
config=run_config)
if FLAGS.do_train:
train_rec_glob = os.path.join(
FLAGS.output_dir,
"{}.*.slen-{}.qlen-{}.train.tf_record".format(
spm_basename, FLAGS.max_seq_length,
FLAGS.max_query_length))
train_input_fn = input_fn_builder(
input_glob=train_rec_glob,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True,
num_hosts=FLAGS.num_hosts)
estimator.train(input_fn=train_input_fn, max_steps=FLAGS.train_steps)
if FLAGS.do_predict:
for eval_set in ['dev','test','challenge']:
new_predict_file = FLAGS.predict_file + "_" + eval_set + ".json"
eval_examples = read_squad_examples(new_predict_file, is_training=False)
with tf.gfile.Open(new_predict_file) as f:
orig_data = json.load(f)["data"]
eval_rec_file = os.path.join(
FLAGS.output_dir,
"{}.slen-{}.qlen-{}.{}.tf_record".format(
spm_basename, FLAGS.max_seq_length, FLAGS.max_query_length, eval_set))
eval_feature_file = os.path.join(
FLAGS.output_dir,
"{}.slen-{}.qlen-{}.{}.features.pkl".format(
spm_basename, FLAGS.max_seq_length, FLAGS.max_query_length, eval_set))
if tf.gfile.Exists(eval_rec_file) and tf.gfile.Exists(
eval_feature_file) and not FLAGS.overwrite_data:
tf.logging.info("Loading eval features from {}".format(eval_feature_file))
with tf.gfile.Open(eval_feature_file, 'rb') as fin:
eval_features = pickle.load(fin)
else:
eval_writer = FeatureWriter(filename=eval_rec_file, is_training=False)
eval_features = []
def append_feature(feature):
eval_features.append(feature)
eval_writer.process_feature(feature)
convert_examples_to_features(
examples=eval_examples,
sp_model=sp_model,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=False,
output_fn=append_feature)
eval_writer.close()
with tf.gfile.Open(eval_feature_file, 'wb') as fout:
pickle.dump(eval_features, fout)
eval_input_fn = input_fn_builder(
input_glob=eval_rec_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=False,
num_hosts=1)
cur_results = []
for result in estimator.predict(
input_fn=eval_input_fn,
yield_single_examples=True):
if len(cur_results) % 1000 == 0:
tf.logging.info("Processing example: %d" % (len(cur_results)))
unique_id = int(result["unique_ids"])
start_top_log_probs = (
[float(x) for x in result["start_top_log_probs"].flat])
start_top_index = [int(x) for x in result["start_top_index"].flat]
end_top_log_probs = (
[float(x) for x in result["end_top_log_probs"].flat])
end_top_index = [int(x) for x in result["end_top_index"].flat]
cur_results.append(
RawResult(
unique_id=unique_id,
start_top_log_probs=start_top_log_probs,
start_top_index=start_top_index,
end_top_log_probs=end_top_log_probs,
end_top_index=end_top_index))
output_prediction_file = os.path.join(
FLAGS.predict_dir, eval_set+"_predictions.json")
output_nbest_file = os.path.join(
FLAGS.predict_dir, eval_set+"_nbest_predictions.json")
ret = write_predictions(eval_examples, eval_features, cur_results,
FLAGS.n_best_size, FLAGS.max_answer_length,
output_prediction_file,
output_nbest_file,
orig_data)
# Log current result
tf.logging.info("=" * 80)
log_str = "Result | "
for key, val in ret.items():
log_str += "{} {} | ".format(key, val)
tf.logging.info(log_str)
tf.logging.info("=" * 80)
if __name__ == "__main__":
tf.app.run()
| 45,164 | 33.9034 | 84 | py |
CLUE | CLUE-master/baselines/models/xlnet/xlnet.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
import tensorflow as tf
import modeling
def _get_initializer(FLAGS):
"""Get variable intializer."""
if FLAGS.init == "uniform":
initializer = tf.initializers.random_uniform(
minval=-FLAGS.init_range,
maxval=FLAGS.init_range,
seed=None)
elif FLAGS.init == "normal":
initializer = tf.initializers.random_normal(
stddev=FLAGS.init_std,
seed=None)
else:
raise ValueError("Initializer {} not supported".format(FLAGS.init))
return initializer
class XLNetConfig(object):
"""XLNetConfig contains hyperparameters that are specific to a model checkpoint;
i.e., these hyperparameters should be the same between
pretraining and finetuning.
The following hyperparameters are defined:
n_layer: int, the number of layers.
d_model: int, the hidden size.
n_head: int, the number of attention heads.
d_head: int, the dimension size of each attention head.
d_inner: int, the hidden size in feed-forward layers.
ff_activation: str, "relu" or "gelu".
untie_r: bool, whether to untie the biases in attention.
n_token: int, the vocab size.
"""
def __init__(self, FLAGS=None, json_path=None):
"""Constructing an XLNetConfig.
One of FLAGS or json_path should be provided."""
assert FLAGS is not None or json_path is not None
self.keys = ["n_layer", "d_model", "n_head", "d_head", "d_inner",
"ff_activation", "untie_r", "n_token"]
if FLAGS is not None:
self.init_from_flags(FLAGS)
if json_path is not None:
self.init_from_json(json_path)
def init_from_flags(self, FLAGS):
for key in self.keys:
setattr(self, key, getattr(FLAGS, key))
def init_from_json(self, json_path):
with tf.gfile.Open(json_path) as f:
json_data = json.load(f)
for key in self.keys:
setattr(self, key, json_data[key])
def to_json(self, json_path):
"""Save XLNetConfig to a json file."""
json_data = {}
for key in self.keys:
json_data[key] = getattr(self, key)
json_dir = os.path.dirname(json_path)
if not tf.gfile.Exists(json_dir):
tf.gfile.MakeDirs(json_dir)
with tf.gfile.Open(json_path, "w") as f:
json.dump(json_data, f, indent=4, sort_keys=True)
def create_run_config(is_training, is_finetune, FLAGS):
kwargs = dict(
is_training=is_training,
use_tpu=FLAGS.use_tpu,
use_bfloat16=FLAGS.use_bfloat16,
dropout=FLAGS.dropout,
dropatt=FLAGS.dropatt,
init=FLAGS.init,
init_range=FLAGS.init_range,
init_std=FLAGS.init_std,
clamp_len=FLAGS.clamp_len)
if not is_finetune:
kwargs.update(dict(
mem_len=FLAGS.mem_len,
reuse_len=FLAGS.reuse_len,
bi_data=FLAGS.bi_data,
clamp_len=FLAGS.clamp_len,
same_length=FLAGS.same_length))
return RunConfig(**kwargs)
class RunConfig(object):
"""RunConfig contains hyperparameters that could be different
between pretraining and finetuning.
These hyperparameters can also be changed from run to run.
We store them separately from XLNetConfig for flexibility.
"""
def __init__(self, is_training, use_tpu, use_bfloat16, dropout, dropatt,
init="normal", init_range=0.1, init_std=0.02, mem_len=None,
reuse_len=None, bi_data=False, clamp_len=-1, same_length=False):
"""
Args:
is_training: bool, whether in training mode.
use_tpu: bool, whether TPUs are used.
use_bfloat16: bool, use bfloat16 instead of float32.
dropout: float, dropout rate.
dropatt: float, dropout rate on attention probabilities.
init: str, the initialization scheme, either "normal" or "uniform".
init_range: float, initialize the parameters with a uniform distribution
in [-init_range, init_range]. Only effective when init="uniform".
init_std: float, initialize the parameters with a normal distribution
with mean 0 and stddev init_std. Only effective when init="normal".
mem_len: int, the number of tokens to cache.
reuse_len: int, the number of tokens in the currect batch to be cached
and reused in the future.
bi_data: bool, whether to use bidirectional input pipeline.
Usually set to True during pretraining and False during finetuning.
clamp_len: int, clamp all relative distances larger than clamp_len.
-1 means no clamping.
same_length: bool, whether to use the same attention length for each token.
"""
self.init = init
self.init_range = init_range
self.init_std = init_std
self.is_training = is_training
self.dropout = dropout
self.dropatt = dropatt
self.use_tpu = use_tpu
self.use_bfloat16 = use_bfloat16
self.mem_len = mem_len
self.reuse_len = reuse_len
self.bi_data = bi_data
self.clamp_len = clamp_len
self.same_length = same_length
class XLNetModel(object):
"""A wrapper of the XLNet model used during both pretraining and finetuning."""
def __init__(self, xlnet_config, run_config, input_ids, seg_ids, input_mask,
mems=None, perm_mask=None, target_mapping=None, inp_q=None,
**kwargs):
"""
Args:
xlnet_config: XLNetConfig,
run_config: RunConfig,
input_ids: int32 Tensor in shape [len, bsz], the input token IDs.
seg_ids: int32 Tensor in shape [len, bsz], the input segment IDs.
input_mask: float32 Tensor in shape [len, bsz], the input mask.
0 for real tokens and 1 for padding.
mems: a list of float32 Tensors in shape [mem_len, bsz, d_model], memory
from previous batches. The length of the list equals n_layer.
If None, no memory is used.
perm_mask: float32 Tensor in shape [len, len, bsz].
If perm_mask[i, j, k] = 0, i attend to j in batch k;
if perm_mask[i, j, k] = 1, i does not attend to j in batch k.
If None, each position attends to all the others.
target_mapping: float32 Tensor in shape [num_predict, len, bsz].
If target_mapping[i, j, k] = 1, the i-th predict in batch k is
on the j-th token.
Only used during pretraining for partial prediction.
Set to None during finetuning.
inp_q: float32 Tensor in shape [len, bsz].
1 for tokens with losses and 0 for tokens without losses.
Only used during pretraining for two-stream attention.
Set to None during finetuning.
"""
initializer = _get_initializer(run_config)
tfm_args = dict(
n_token=xlnet_config.n_token,
initializer=initializer,
attn_type="bi",
n_layer=xlnet_config.n_layer,
d_model=xlnet_config.d_model,
n_head=xlnet_config.n_head,
d_head=xlnet_config.d_head,
d_inner=xlnet_config.d_inner,
ff_activation=xlnet_config.ff_activation,
untie_r=xlnet_config.untie_r,
is_training=run_config.is_training,
use_bfloat16=run_config.use_bfloat16,
use_tpu=run_config.use_tpu,
dropout=run_config.dropout,
dropatt=run_config.dropatt,
mem_len=run_config.mem_len,
reuse_len=run_config.reuse_len,
bi_data=run_config.bi_data,
clamp_len=run_config.clamp_len,
same_length=run_config.same_length
)
input_args = dict(
inp_k=input_ids,
seg_id=seg_ids,
input_mask=input_mask,
mems=mems,
perm_mask=perm_mask,
target_mapping=target_mapping,
inp_q=inp_q)
tfm_args.update(input_args)
with tf.variable_scope("model", reuse=tf.AUTO_REUSE):
(self.output, self.new_mems, self.lookup_table
) = modeling.transformer_xl(**tfm_args)
self.input_mask = input_mask
self.initializer = initializer
self.xlnet_config = xlnet_config
self.run_config = run_config
def get_pooled_out(self, summary_type, use_summ_proj=True):
"""
Args:
summary_type: str, "last", "first", "mean", or "attn". The method
to pool the input to get a vector representation.
use_summ_proj: bool, whether to use a linear projection during pooling.
Returns:
float32 Tensor in shape [bsz, d_model], the pooled representation.
"""
xlnet_config = self.xlnet_config
run_config = self.run_config
with tf.variable_scope("model", reuse=tf.AUTO_REUSE):
summary = modeling.summarize_sequence(
summary_type=summary_type,
hidden=self.output,
d_model=xlnet_config.d_model,
n_head=xlnet_config.n_head,
d_head=xlnet_config.d_head,
dropout=run_config.dropout,
dropatt=run_config.dropatt,
is_training=run_config.is_training,
input_mask=self.input_mask,
initializer=self.initializer,
use_proj=use_summ_proj)
return summary
def get_sequence_output(self):
"""
Returns:
float32 Tensor in shape [len, bsz, d_model]. The last layer hidden
representation of XLNet.
"""
return self.output
def get_new_memory(self):
"""
Returns:
list of float32 Tensors in shape [mem_len, bsz, d_model], the new
memory that concatenates the previous memory with the current input
representations.
The length of the list equals n_layer.
"""
return self.new_mems
def get_embedding_table(self):
"""
Returns:
float32 Tensor in shape [n_token, d_model]. The embedding lookup table.
Used for tying embeddings between input and output layers.
"""
return self.lookup_table
def get_initializer(self):
"""
Returns:
A tf initializer. Used to initialize variables in layers on top of XLNet.
"""
return self.initializer
| 9,838 | 32.580205 | 82 | py |
CLUE | CLUE-master/baselines/models/xlnet/gpu_utils.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
def assign_to_gpu(gpu=0, ps_dev="/device:CPU:0"):
def _assign(op):
node_def = op if isinstance(op, tf.NodeDef) else op.node_def
if node_def.op == "Variable":
return ps_dev
else:
return "/gpu:%d" % gpu
return _assign
def average_grads_and_vars(tower_grads_and_vars):
def average_dense(grad_and_vars):
if len(grad_and_vars) == 1:
return grad_and_vars[0][0]
grad = grad_and_vars[0][0]
for g, _ in grad_and_vars[1:]:
grad += g
return grad / len(grad_and_vars)
def average_sparse(grad_and_vars):
if len(grad_and_vars) == 1:
return grad_and_vars[0][0]
indices = []
values = []
for g, _ in grad_and_vars:
indices += [g.indices]
values += [g.values]
indices = tf.concat(indices, 0)
values = tf.concat(values, 0) / len(grad_and_vars)
return tf.IndexedSlices(values, indices, grad_and_vars[0][0].dense_shape)
average_grads_and_vars = []
for grad_and_vars in zip(*tower_grads_and_vars):
if grad_and_vars[0][0] is None:
grad = None
elif isinstance(grad_and_vars[0][0], tf.IndexedSlices):
grad = average_sparse(grad_and_vars)
else:
grad = average_dense(grad_and_vars)
# Keep in mind that the Variables are redundant because they are shared
# across towers. So .. we will just return the first tower's pointer to
# the Variable.
v = grad_and_vars[0][1]
grad_and_var = (grad, v)
average_grads_and_vars.append(grad_and_var)
return average_grads_and_vars
def load_from_checkpoint(saver, logdir):
sess = tf.get_default_session()
ckpt = tf.train.get_checkpoint_state(logdir)
if ckpt and ckpt.model_checkpoint_path:
if os.path.isabs(ckpt.model_checkpoint_path):
# Restores from checkpoint with absolute path.
saver.restore(sess, ckpt.model_checkpoint_path)
else:
# Restores from checkpoint with relative path.
saver.restore(sess, os.path.join(logdir, ckpt.model_checkpoint_path))
return True
return False
| 2,358 | 32.7 | 81 | py |
CLUE | CLUE-master/baselines/models/xlnet/tpu_estimator.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===================================================================
"""TPUEstimator class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import os
import signal
import sys
import threading
import time
import numpy as np
import six
from six.moves import queue as Queue # pylint: disable=redefined-builtin
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.contrib.tpu.proto import compilation_result_pb2 as tpu_compilation_result
from tensorflow.contrib.tpu.python.tpu import tensor_tracer
from tensorflow.contrib.tpu.python.ops import tpu_ops
from tensorflow.contrib.tpu.python.tpu import error_handling
from tensorflow.contrib.tpu.python.tpu import session_support
from tensorflow.contrib.tpu.python.tpu import tpu
from tensorflow.contrib.tpu.python.tpu import tpu_config
from tensorflow.contrib.tpu.python.tpu import tpu_context
from tensorflow.contrib.tpu.python.tpu import tpu_feed
from tensorflow.contrib.tpu.python.tpu import training_loop
from tensorflow.contrib.tpu.python.tpu import util as util_lib
from tensorflow.contrib.training.python.training import hparam
from tensorflow.core.framework import variable_pb2
from tensorflow.core.framework.summary_pb2 import Summary
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session as tf_session
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.util import nest as data_nest
from tensorflow.python.estimator import estimator as estimator_lib
from tensorflow.python.estimator import model_fn as model_fn_lib
from tensorflow.python.estimator.export import export_output as export_output_lib
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import summary_ops_v2 as contrib_summary
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.saved_model import tag_constants
from tensorflow.python.summary import summary
from tensorflow.python.training import basic_session_run_hooks
from tensorflow.python.training import evaluation
from tensorflow.python.training import session_run_hook
from tensorflow.python.training import training
from tensorflow.python.training import training_util
from tensorflow.python.util import function_utils
from tensorflow.python.util import nest
from tensorflow.python.util import tf_inspect
_INITIAL_LOSS = 1e7
_ZERO_LOSS = 0.
_TPU_ESTIMATOR = 'custom_tpu_estimator'
_ITERATIONS_PER_LOOP_VAR = 'iterations_per_loop'
_BATCH_SIZE_KEY = 'batch_size'
_CTX_KEY = 'context'
_USE_TPU_KEY = 'use_tpu'
_CROSS_REPLICA_SUM_OP = 'CrossReplicaSum'
_ONE_GIGABYTE = 1024 * 1024 * 1024
_TPU_ENQUEUE_OPS = '_tpu_enqueue_ops'
_TPU_TRAIN_OP = '_tpu_train_op'
_REWRITE_FOR_INFERENCE_MODE = '_rewrite_for_inference'
# Ideally _USE_TPU_KEY should be reserved as well. However there are already
# models that make use of this key, thus it can not be reserved now to prevent
# breakage. In the long run, we would like to mitigate this by migrating models
# off of using _USE_TPU_KEY.
_RESERVED_PARAMS_KEYS = [_BATCH_SIZE_KEY, _CTX_KEY]
# TODO(b/65703635): Flip the value and remove all dead code. Currently, this is
# only used for per-core based deployments. For per-host based pipelines, if a
# user returns a Dataset instance it will be automatically wrapped in a
# tf.while_loop (This can be disabled by returning features and labels
# explicitly).
_WRAP_INPUT_FN_INTO_WHILE_LOOP = False
ops.register_proto_function(
'{}_{}'.format(_TPU_ESTIMATOR, _ITERATIONS_PER_LOOP_VAR),
proto_type=variable_pb2.VariableDef,
to_proto=resource_variable_ops._to_proto_fn, # pylint: disable=protected-access
from_proto=resource_variable_ops._from_proto_fn) # pylint: disable=protected-access
def _is_iterable(obj):
"""A Python 2 and 3 compatible util to check whether `obj` is iterable."""
try:
iter(obj)
return True
except TypeError:
return False
def _create_global_step(graph):
graph = graph or ops.get_default_graph()
if training.get_global_step(graph) is not None:
raise ValueError('"global_step" already exists.')
# Create in proper graph and base name_scope.
with graph.as_default() as g, g.name_scope(None):
return variable_scope.get_variable(
ops.GraphKeys.GLOBAL_STEP,
shape=[],
dtype=dtypes.int64,
initializer=init_ops.zeros_initializer(),
trainable=False,
use_resource=True,
collections=[ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.GLOBAL_STEP])
def _create_or_get_iterations_per_loop():
"""Creates or gets the iterations_per_loop variable.
In TPUEstimator, the user provided computation, the model_fn, is wrapped
inside a tf.while_loop for peak performance. The iterations of the loop are
specified by this variable, which adjusts its value on the CPU after each TPU
program execution and before the next TPU execution.
The purpose of using a variable, rather then a constant, is to allow
TPUEstimator adapt the TPU training iterations according to the final steps
specified by users. For example, if the user sets the iterations_per_loop as 4
in TPUConfig and steps as 10 in TPUEstimator.train(), the iterations_per_loop
variable will have the following value before each TPU training.
- 1-th TPU execution: iterations_per_loop = 4
- 2-th TPU execution: iterations_per_loop = 4
- 3-th TPU execution: iterations_per_loop = 2
As model_fn increases the global step once per train_op invocation, the global
step is 10 after all TPU executions, matching the steps=10 inputs passed in by
users.
Returns:
A TF non-trainable resource variable.
Raises:
RuntimeError: If multi iterations_per_loop variables were found.
"""
graph = ops.get_default_graph()
collection_name = '{}_{}'.format(_TPU_ESTIMATOR, _ITERATIONS_PER_LOOP_VAR)
iter_vars = graph.get_collection(collection_name)
if len(iter_vars) == 1:
return iter_vars[0]
elif len(iter_vars) > 1:
raise RuntimeError('Multiple iterations_per_loop_var in collection.')
with ops.colocate_with(training_util.get_global_step()):
with variable_scope.variable_scope(
_TPU_ESTIMATOR, reuse=variable_scope.AUTO_REUSE):
return variable_scope.get_variable(
_ITERATIONS_PER_LOOP_VAR,
initializer=init_ops.zeros_initializer(),
shape=[],
dtype=dtypes.int32,
trainable=False,
collections=[collection_name, ops.GraphKeys.LOCAL_VARIABLES],
use_resource=True)
def _sync_variables_ops(ctx):
"""Create varriables synchronization ops.
Gets the variables back from TPU nodes. This means the variables updated
by TPU will now be *synced* to host memory.
In BROADCAST mode, we skip this sync since the variables are ususally too
big to transmit via RPC.
Args:
ctx: A `_InternalTPUContext` instance with mode.
Returns:
A list of sync ops.
"""
if not ctx.is_input_broadcast_with_iterators():
return [
array_ops.check_numerics(v.read_value(),
'Gradient for %s is NaN' % v.name).op
for v in variables.trainable_variables()
]
else:
return [control_flow_ops.no_op()]
def _increase_eval_step_op(iterations_per_loop):
"""Returns an op to increase the eval step for TPU evaluation.
Args:
iterations_per_loop: Tensor. The number of eval steps running in TPU system
before returning to CPU host for each `Session.run`.
Returns:
An operation
"""
eval_step = evaluation._get_or_create_eval_step() # pylint: disable=protected-access
# Estimator evaluate increases 1 by default. So, we increase the difference.
return state_ops.assign_add(
eval_step,
math_ops.cast(iterations_per_loop - 1, dtype=eval_step.dtype),
use_locking=True)
def _extract_key_names(tensor_or_dict):
if isinstance(tensor_or_dict, dict):
return sorted(tensor_or_dict.keys())
return []
class _SIGNAL(object):
"""Signal used to control the thread of infeed/outfeed.
All preserved signals must be negative numbers. Positive numbers are used to
indicate the number of iterations for next training/evaluation loop.
"""
NEXT_BATCH = -1
STOP = -2
class TPUEstimatorSpec(model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access
"""Ops and objects returned from a `model_fn` and passed to `TPUEstimator`.
See `EstimatorSpec` for `mode`, `predictions`, `loss`, `train_op`, and
`export_outputs`.
For evaluation, `eval_metrics `is a tuple of `metric_fn` and `tensors`, where
`metric_fn` runs on CPU to generate metrics and `tensors` represents the
`Tensor`s transferred from TPU system to CPU host and passed to `metric_fn`.
To be precise, TPU evaluation expects a slightly different signature from the
`tf.estimator.Estimator`. While `EstimatorSpec.eval_metric_ops` expects a
dict, `TPUEstimatorSpec.eval_metrics` is a tuple of `metric_fn` and `tensors`.
The `tensors` could be a list of `Tensor`s or dict of names to `Tensor`s. The
`tensors` usually specify the model logits, which are transferred back from
TPU system to CPU host. All tensors must have be batch-major, i.e., the batch
size is the first dimension. Once all tensors are available at CPU host from
all shards, they are concatenated (on CPU) and passed as positional arguments
to the `metric_fn` if `tensors` is list or keyword arguments if `tensors` is
a dict. `metric_fn` takes the `tensors` and returns a dict from metric string
name to the result of calling a metric function, namely a `(metric_tensor,
update_op)` tuple. See `TPUEstimator` for MNIST example how to specify the
`eval_metrics`.
`scaffold_fn` is a function running on CPU to generate the `Scaffold`. This
function should not capture any Tensors in `model_fn`.
`host_call` is a tuple of a `function` and a list or dictionary of `tensors`
to pass to that function and returns a list of Tensors. `host_call` currently
works for train() and evaluate(). The Tensors returned by the function is
executed on the CPU on every step, so there is communication overhead when
sending tensors from TPU to CPU. To reduce the overhead, try reducing the
size of the tensors. The `tensors` are concatenated along their major (batch)
dimension, and so must be >= rank 1. The `host_call` is useful for writing
summaries with `tf.contrib.summary.create_file_writer`.
"""
def __new__(cls,
mode,
predictions=None,
loss=None,
train_op=None,
eval_metrics=None,
export_outputs=None,
scaffold_fn=None,
host_call=None,
training_hooks=None,
evaluation_hooks=None,
prediction_hooks=None):
"""Creates a validated `TPUEstimatorSpec` instance."""
host_calls = {}
if eval_metrics is not None:
host_calls['eval_metrics'] = eval_metrics
if host_call is not None:
host_calls['host_call'] = host_call
_OutfeedHostCall.validate(host_calls)
training_hooks = tuple(training_hooks or [])
evaluation_hooks = tuple(evaluation_hooks or [])
prediction_hooks = tuple(prediction_hooks or [])
for hook in training_hooks + evaluation_hooks + prediction_hooks:
if not isinstance(hook, session_run_hook.SessionRunHook):
raise TypeError('All hooks must be SessionRunHook instances, given: {}'
.format(hook))
return super(TPUEstimatorSpec, cls).__new__(
cls,
mode=mode,
predictions=predictions,
loss=loss,
train_op=train_op,
eval_metrics=eval_metrics,
export_outputs=export_outputs,
scaffold_fn=scaffold_fn,
host_call=host_call,
training_hooks=training_hooks,
evaluation_hooks=evaluation_hooks,
prediction_hooks=prediction_hooks)
def as_estimator_spec(self):
"""Creates an equivalent `EstimatorSpec` used by CPU train/eval."""
host_calls = {}
if self.eval_metrics is not None:
host_calls['eval_metrics'] = self.eval_metrics
if self.host_call is not None:
host_calls['host_call'] = self.host_call
host_call_ret = _OutfeedHostCall.create_cpu_hostcall(host_calls)
eval_metric_ops = None
if self.eval_metrics is not None:
eval_metric_ops = host_call_ret['eval_metrics']
hooks = None
if self.host_call is not None:
hooks = [_OutfeedHostCallHook(host_call_ret['host_call'])]
if tensor_tracer.TensorTracer.is_enabled():
tt = tensor_tracer.TensorTracer()
tracing_calls = tt.trace_cpu(ops.get_default_graph())
tracing_call_ret = _OutfeedHostCall.create_cpu_hostcall(tracing_calls)
tracing_functions = tracing_call_ret.values()
if tracing_functions:
if hooks:
hooks.extend([_OutfeedHostCallHook(tracing_functions)])
else:
hooks = [_OutfeedHostCallHook(tracing_functions)]
hooks = tuple(hooks or [])
scaffold = self.scaffold_fn() if self.scaffold_fn else None
return model_fn_lib.EstimatorSpec(
mode=self.mode,
predictions=self.predictions,
loss=self.loss,
train_op=self.train_op,
eval_metric_ops=eval_metric_ops,
export_outputs=self.export_outputs,
scaffold=scaffold,
training_hooks=self.training_hooks + hooks,
evaluation_hooks=self.evaluation_hooks + hooks,
prediction_hooks=self.prediction_hooks + hooks)
class _OpQueueContext(object):
"""Manages work queue and thread for a infeed/outfeed thread."""
def __init__(self, name, target, args):
self._name = name
self._queue = Queue.Queue()
args = (self,) + args
self._thread = threading.Thread(name=name, target=target, args=args)
self._thread.daemon = True
self._thread.start()
def stop(self):
self._queue.put(_SIGNAL.STOP)
def send_next_batch_signal(self, iterations):
self._queue.put(iterations)
def read_iteration_counts(self):
while True:
iterations = self._queue.get(block=True)
logging.debug('%s read iterations %s', self._name, iterations)
if iterations == _SIGNAL.STOP:
logging.info('%s received shutdown signal, stopping.', self._name)
return
yield iterations
def join(self):
logging.info('Shutting down %s thread.', self._name)
self.stop()
self._thread.join()
class _OpSignalOnceQueueContext(_OpQueueContext):
"""Manages work queue and thread for a infeed/outfeed thread.
This subclass only signals once.
"""
def __init__(self, name, target, args):
super(_OpSignalOnceQueueContext, self).__init__(name, target, args)
self._has_signaled = False
def send_next_batch_signal(self, iterations):
if not self._has_signaled:
self._queue.put(iterations)
self._has_signaled = True
class TPUInfeedOutfeedSessionHook(session_run_hook.SessionRunHook):
"""A Session hook setting up the TPU initialization, infeed, and outfeed.
This hook does two major things:
1. initialize and shutdown TPU system.
2. launch and join the threads for infeed enqueue and (optional) outfeed
dequeue.
"""
def __init__(self,
ctx,
enqueue_ops,
dequeue_ops,
tpu_compile_op,
run_infeed_loop_on_coordinator=True,
rendezvous=None,
master=None,
session_config=None):
self._master_job = ctx.master_job
self._enqueue_ops = enqueue_ops
self._dequeue_ops = dequeue_ops
self._rendezvous = rendezvous
self._master = master
self._session_config = session_config
self._run_infeed_loop_on_coordinator = run_infeed_loop_on_coordinator
self._initial_infeed_sleep_secs = (
ctx.config.tpu_config.initial_infeed_sleep_secs)
self._feed_error = None
self._finished = False
self._should_initialize_tpu = True
self._tpu_compile_op = tpu_compile_op
def begin(self):
logging.info('TPU job name %s', self._master_job)
self._iterations_per_loop_var = _create_or_get_iterations_per_loop()
self._init_ops = []
if self._should_initialize_tpu:
self._finalize_ops = [tpu.shutdown_system(job=self._master_job)]
else:
self._finalize_ops = []
summary_writer_init_ops = contrib_summary.summary_writer_initializer_op()
self._init_ops.extend(summary_writer_init_ops)
# Get all the writer resources from the initializer, so we know what to
# flush.
for op in summary_writer_init_ops:
self._finalize_ops.append(contrib_summary.flush(writer=op.inputs[0]))
def _run_infeed(self, queue_ctx, session):
logging.info('Starting infeed thread controller.')
if self._initial_infeed_sleep_secs:
logging.info('Infeed thread sleeping for %d seconds.',
self._initial_infeed_sleep_secs)
time.sleep(self._initial_infeed_sleep_secs)
logging.info('Infeed thread starting after sleep')
with self._rendezvous.catch_errors(source='infeed', session=session):
if self._run_infeed_loop_on_coordinator:
for count, steps in enumerate(queue_ctx.read_iteration_counts()):
for i in xrange(steps):
logging.debug('Infeed enqueue for iteration (%d, %d)', count, i)
session.run(self._enqueue_ops)
else:
for _ in queue_ctx.read_iteration_counts():
session.run(self._enqueue_ops)
logging.info('Infeed thread finished, shutting down.')
def _run_outfeed(self, queue_ctx, session):
logging.info('Starting outfeed thread controller.')
with self._rendezvous.catch_errors(source='outfeed', session=session):
for count, steps in enumerate(queue_ctx.read_iteration_counts()):
for i in xrange(steps):
logging.debug('Outfeed dequeue for iteration (%d, %d)', count, i)
session.run(self._dequeue_ops)
logging.info('Outfeed thread finished, shutting down.')
def _create_infeed_controller(self, name, target, args):
return _OpQueueContext(name=name, target=target, args=args)
def _assertCompilationSucceeded(self, result, coord):
proto = tpu_compilation_result.CompilationResultProto()
proto.ParseFromString(result)
if proto.status_error_message:
logging.error('Compilation failed: {}'.format(proto.status_error_message))
coord.request_stop()
else:
logging.info('Compilation succeeded')
def after_create_session(self, session, coord):
if self._should_initialize_tpu:
logging.info('Init TPU system')
start = time.time()
with ops.Graph().as_default():
with tf_session.Session(
self._master, config=self._session_config) as sess:
sess.run(tpu.initialize_system(job=self._master_job))
logging.info('Initialized TPU in %d seconds', time.time() - start)
session.run(self._init_ops,
options=config_pb2.RunOptions(timeout_in_ms=5 * 60 * 1000))
if os.environ.get('TPU_SPLIT_COMPILE_AND_EXECUTE', '') == '1':
logging.info('Compiling user program: this may take a while...')
self._assertCompilationSucceeded(session.run(self._tpu_compile_op), coord)
self._infeed_controller = self._create_infeed_controller(
name='InfeedController', target=self._run_infeed, args=(session,))
self._outfeed_controller = _OpQueueContext(
name='OutfeedController', target=self._run_outfeed, args=(session,))
# Enable the worker watchdog to terminate workers on coordinator exit.
watchdog_timeout = int(os.environ.get('TF_TPU_WATCHDOG_TIMEOUT', '0'))
if watchdog_timeout > 0:
session_support.start_worker_watchdog(session,
shutdown_timeout=watchdog_timeout)
def before_run(self, run_context):
self._feed_error = None
iterations = run_context.session.run(self._iterations_per_loop_var)
logging.info('Enqueue next (%d) batch(es) of data to infeed.', iterations)
self._infeed_controller.send_next_batch_signal(iterations)
logging.info('Dequeue next (%d) batch(es) of data from outfeed.',
iterations)
self._outfeed_controller.send_next_batch_signal(iterations)
def end(self, session):
self._finished = True
logging.info('Stop infeed thread controller')
self._infeed_controller.join()
self._rendezvous.record_done('infeed')
logging.info('Stop output thread controller')
self._outfeed_controller.join()
self._rendezvous.record_done('outfeed')
logging.info('Shutdown TPU system.')
session.run(self._finalize_ops)
class TPUInfeedOutfeedSessionHookForPrediction(TPUInfeedOutfeedSessionHook):
def __init__(self, ctx, enqueue_ops, dequeue_ops, tpu_compile_op,
rendezvous=None, master=None, session_config=None):
super(TPUInfeedOutfeedSessionHookForPrediction, self).__init__(
ctx,
enqueue_ops,
dequeue_ops,
tpu_compile_op=tpu_compile_op,
run_infeed_loop_on_coordinator=False,
rendezvous=rendezvous,
master=master,
session_config=session_config)
def _create_infeed_controller(self, name, target, args):
return _OpSignalOnceQueueContext(name=name, target=target, args=args)
class _TPUStopAtStepHook(session_run_hook.SessionRunHook):
"""Hook that requests stop at a specified step.
This hook is similar to the `session_run_hook._StopAfterNEvalsHook` with
following differences for TPU training:
1. This hook sets the variable for iterations_per_loop, which is used by
`TPUInfeedOutfeedSessionHook` to control the iterations for infeed/outfeed.
As the hook execution order is not guaranteed, the variable update is
handled in `after_create_session` and `after_run` as
`TPUInfeedOutfeedSessionHook` reads the variable value in `before_run`.
2. For each training loop (session.run), the global step could be increased
multiple times on TPU. The global step tensor value will be explicitly read
again in `after_run` to ensure the latest value is retrieved to avoid race
condition.
"""
def __init__(self, iterations, num_steps=None, last_step=None):
"""Initializes a `StopAtStepHook`.
Args:
iterations: The number of iterations to run optimizer per training loop.
num_steps: Number of steps to execute.
last_step: Step after which to stop.
Raises:
ValueError: If one of the arguments is invalid.
"""
if num_steps is None and last_step is None:
raise ValueError('One of num_steps or last_step must be specified.')
if num_steps is not None and last_step is not None:
raise ValueError('Only one of num_steps or last_step can be specified.')
self._num_steps = num_steps
self._last_step = last_step
self._iterations = iterations
def _next_iterations(self, global_step, last_step):
gap = last_step - global_step
return min(gap, self._iterations)
def begin(self):
self._global_step_tensor = training_util.get_global_step()
if self._global_step_tensor is None:
raise RuntimeError('Global step should be created.')
self._iterations_per_loop_var = _create_or_get_iterations_per_loop()
def after_create_session(self, session, coord):
global_step = session.run(self._global_step_tensor)
if self._last_step is None:
self._last_step = global_step + self._num_steps
iterations = self._next_iterations(global_step, self._last_step)
self._iterations_per_loop_var.load(iterations, session=session)
def after_run(self, run_context, run_values):
# Global step cannot be retrieved via SessionRunArgs and before_run due to
# race condition.
global_step = run_context.session.run(self._global_step_tensor)
if global_step >= self._last_step:
run_context.request_stop()
else:
iterations = self._next_iterations(global_step, self._last_step)
self._iterations_per_loop_var.load(
iterations, session=run_context.session)
class _SetEvalIterationsHook(session_run_hook.SessionRunHook):
"""Hook that requests stop at a specified step."""
def __init__(self, num_steps):
"""Initializes a `_SetEvalIterationsHook`.
Args:
num_steps: Number of steps to execute.
"""
self._num_steps = num_steps
def begin(self):
self._iterations_per_loop_var = _create_or_get_iterations_per_loop()
def after_create_session(self, session, coord):
self._iterations_per_loop_var.load(self._num_steps, session=session)
class _StoppingPredictHook(session_run_hook.SessionRunHook):
"""Hook that requests stop according to the stopping signal in prediction."""
def __init__(self, scalar_stopping_signal):
self._scalar_stopping_signal = scalar_stopping_signal
def begin(self):
self._iterations_per_loop_var = _create_or_get_iterations_per_loop()
def after_create_session(self, session, coord):
# This is not necessary as we do not run infeed enqueue and outfeed dequeue
# in side threads for prediction model. But it makes the
# TPUInfeedOutfeedSessionHook prints nice message.
self._iterations_per_loop_var.load(1, session=session)
def before_run(self, run_context):
return session_run_hook.SessionRunArgs(self._scalar_stopping_signal)
def after_run(self, run_context, run_values):
_ = run_context
scalar_stopping_signal = run_values.results
if _StopSignals.should_stop(scalar_stopping_signal):
# NOTE(xiejw): In prediction, stopping signals are inserted for each
# batch. And we append one more batch to signal the system it should stop.
# The data flow might look like
#
# batch 0: images, labels, stop = 0 (user provided)
# batch 1: images, labels, stop = 0 (user provided)
# ...
# batch 99: images, labels, stop = 0 (user provided)
# batch 100: images, labels, stop = 1 (TPUEstimator appended)
#
# where the final batch (id = 100) is appended by TPUEstimator, so we
# should drop it before returning the predictions to user.
# To achieve that, we throw the OutOfRangeError in after_run. Once
# Monitored Session sees this error in SessionRunHook.after_run, the
# "current" prediction, i.e., batch with id=100, will be discarded
# immediately
raise errors.OutOfRangeError(None, None, 'Stopped by stopping signal.')
def generate_per_core_enqueue_ops_fn_for_host(
ctx, input_fn, inputs_structure_recorder, host_device, host_id):
"""Generates infeed enqueue ops for per-core input_fn on a single host."""
captured_infeed_queue = _CapturedObject()
tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id)
def enqueue_ops_fn():
"""A fn returns enqueue_ops."""
num_cores_per_host = ctx.num_of_cores_per_host
per_host_sharded_inputs = []
for core_ordinal in range(num_cores_per_host):
with ops.name_scope('ordinal_%d' % (core_ordinal)):
user_context = tpu_context.TPUContext(
internal_ctx=ctx,
input_device=host_device,
invocation_index=host_id * ctx.num_of_cores_per_host + core_ordinal)
inputs = _Inputs.from_input_fn(input_fn(user_context))
if inputs.is_dataset:
raise TypeError(
'`input_fn` returning `Dataset` is not yet supported in '
'per-Core input pipeline deployment yet. Please set '
'TPUConfig.per_host_input_for_training to True or return '
'`features` and `labels` from `input_fn`')
features, labels = inputs.features_and_labels()
inputs_structure_recorder.validate_and_record_structure(
features, labels)
flattened_inputs = (
inputs_structure_recorder.flatten_features_and_labels(
features, labels))
per_host_sharded_inputs.append(flattened_inputs)
infeed_queue = tpu_feed.InfeedQueue(
number_of_tuple_elements=len(per_host_sharded_inputs[0]))
captured_infeed_queue.capture(infeed_queue)
per_host_enqueue_ops = infeed_queue.generate_enqueue_ops(
per_host_sharded_inputs, tpu_ordinal_function=tpu_ordinal_function_impl)
return per_host_enqueue_ops
return enqueue_ops_fn, captured_infeed_queue
def generate_per_host_enqueue_ops_fn_for_host(
ctx, input_fn, inputs_structure_recorder, batch_axis, device, host_id):
"""Generates infeed enqueue ops for per-host input_fn on a single host."""
captured_infeed_queue = _CapturedObject()
dataset_initializer = None
with ops.device(device):
user_context = tpu_context.TPUContext(
internal_ctx=ctx, input_device=device, invocation_index=host_id)
inputs = _Inputs.from_input_fn(input_fn(user_context))
is_dataset = inputs.is_dataset
if ctx.mode == model_fn_lib.ModeKeys.PREDICT:
if not is_dataset:
raise TypeError(
'For mode PREDICT, `input_fn` must return `Dataset` instead of '
'`features` and `labels`.')
if batch_axis is not None:
raise TypeError('For mode PREDICT, batch_axis is not supported yet.')
inputs = _InputsWithStoppingSignals(
dataset=inputs.dataset,
batch_size=ctx.batch_size_for_input_fn,
add_padding=True)
if is_dataset:
dataset_initializer = inputs.dataset_initializer()
tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id)
def enqueue_ops_fn():
"""A Fn returning the TPU infeed enqueue ops.
By providing as a Fn, it can be invoked inside the tf.while_loop such that
the input pipeline for multiple iterations can be executed by one
Session.run call.
Returns:
list of dict of ops.
"""
with ops.device(device):
num_of_replicas_per_host = ctx.num_of_replicas_per_host
# Convert user input to features and labels. If the user returns a
# dataset, it is initialized and the features and labels extracted via
# `dataset.iterator.get_next()`
features, labels = inputs.features_and_labels()
signals = inputs.signals()
inputs_structure_recorder.validate_and_record_structure(features, labels)
unsharded_tensor_list = (
inputs_structure_recorder.flatten_features_and_labels(
features, labels, signals))
infeed_queue = tpu_feed.InfeedQueue(
tuple_types=[t.dtype for t in unsharded_tensor_list],
tuple_shapes=[t.shape for t in unsharded_tensor_list],
shard_dimensions=batch_axis)
captured_infeed_queue.capture(infeed_queue)
infeed_queue.set_number_of_shards(num_of_replicas_per_host)
per_host_enqueue_ops = (
infeed_queue.split_inputs_and_generate_enqueue_ops(
unsharded_tensor_list,
placement_function=lambda x: device,
tpu_ordinal_function=tpu_ordinal_function_impl))
if signals is None:
return per_host_enqueue_ops
else:
return {
'ops': per_host_enqueue_ops,
'signals': signals,
}
return enqueue_ops_fn, captured_infeed_queue, dataset_initializer
def generate_per_host_v2_enqueue_ops_fn_for_host(
ctx, input_fn, inputs_structure_recorder, device, host_id):
"""Generates infeed enqueue ops for per-host input_fn on a single host."""
captured_infeed_queue = _CapturedObject()
dataset_initializer = None
with ops.device(device):
user_context = tpu_context.TPUContext(
internal_ctx=ctx, input_device=device, invocation_index=host_id)
inputs = _Inputs.from_input_fn(input_fn(user_context))
is_dataset = inputs.is_dataset
if not is_dataset:
raise TypeError('`input_fn` must return a `Dataset` for the PER_HOST_V2 '
'input pipeline configuration.')
if ctx.mode == model_fn_lib.ModeKeys.PREDICT:
inputs = _InputsWithStoppingSignals(
dataset=inputs.dataset,
batch_size=ctx.batch_size_for_input_fn,
add_padding=True,
num_invocations_per_step=ctx.num_of_replicas_per_host)
dataset_initializer = inputs.dataset_initializer()
tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id)
def enqueue_ops_fn():
"""Generates the per_host enqueue ops."""
control_deps = []
per_host_sharded_inputs = []
num_replicas_per_host = ctx.num_of_replicas_per_host
cached_signals = None
with ops.device(device):
if not inputs.is_dataset:
raise TypeError('`input_fn` must return a `Dataset` for this mode.')
for _ in range(num_replicas_per_host):
# Use control dependencies to ensure a deterministic ordering.
with ops.control_dependencies(control_deps):
features, labels = inputs.features_and_labels() # Calls get_next()
signals = inputs.signals()
# All the replicas share the replica 0's stopping singal.
# This avoids inconsistent state among different model replcias.
if cached_signals:
signals['stopping'] = cached_signals['stopping']
else:
cached_signals = signals
inputs_structure_recorder.validate_and_record_structure(
features, labels)
flattened_inputs = (
inputs_structure_recorder.flatten_features_and_labels(
features, labels, signals))
control_deps.extend(flattened_inputs)
per_host_sharded_inputs.append(flattened_inputs)
if inputs_structure_recorder.flattened_input_dims:
input_partition_dims = inputs_structure_recorder.flattened_input_dims
if signals:
input_partition_dims += [None] * len(signals)
# pylint: disable=protected-access
infeed_queue = tpu_feed._PartitionedInfeedQueue(
number_of_tuple_elements=len(per_host_sharded_inputs[0]),
host_id=host_id,
input_partition_dims=input_partition_dims,
device_assignment=ctx.device_assignment)
per_host_enqueue_ops = infeed_queue.generate_enqueue_ops(
per_host_sharded_inputs)
else:
infeed_queue = tpu_feed.InfeedQueue(
number_of_tuple_elements=len(per_host_sharded_inputs[0]))
per_host_enqueue_ops = infeed_queue.generate_enqueue_ops(
per_host_sharded_inputs,
tpu_ordinal_function=tpu_ordinal_function_impl)
captured_infeed_queue.capture(infeed_queue)
if signals is None:
return per_host_enqueue_ops
else:
return {
'ops': per_host_enqueue_ops,
'signals': signals,
}
return enqueue_ops_fn, captured_infeed_queue, dataset_initializer
def generate_broadcast_enqueue_ops_fn(ctx, input_fn, inputs_structure_recorder,
num_hosts):
"""Generates infeed enqueue ops for one input_fn on all the hosts."""
captured_infeed_queue = _CapturedObject()
dataset_initializer = None
device_0 = ctx.tpu_host_placement_function(host_id=0)
with ops.device(device_0):
user_context = tpu_context.TPUContext(
internal_ctx=ctx, input_device=device_0, invocation_index=0)
inputs = _Inputs.from_input_fn(input_fn(user_context))
is_dataset = inputs.is_dataset
if ctx.mode == model_fn_lib.ModeKeys.PREDICT:
if not is_dataset:
raise TypeError(
'For mode PREDICT, `input_fn` must return `Dataset` instead of '
'`features` and `labels`.')
inputs = _InputsWithStoppingSignals(
dataset=inputs.dataset,
batch_size=ctx.batch_size_for_input_fn,
add_padding=True)
if is_dataset:
dataset_initializer = inputs.dataset_initializer()
num_replicas_per_host = ctx.num_of_replicas_per_host
def tpu_ordinal_function_impl(replica_id):
if ctx.device_assignment:
return ctx.device_assignment.tpu_ordinal(replica=replica_id)
else:
return replica_id % num_replicas_per_host
def device_function_impl(replica_id):
return ctx.tpu_host_placement_function(replica_id=replica_id)
def enqueue_ops_fn():
"""Generates enqueue ops for all the hosts."""
broadcasted_inputs = []
flattened_inputs = None # Cache result from input_fn.
signals = None
for host_id in xrange(num_hosts):
with ops.device(ctx.tpu_host_placement_function(host_id=host_id)):
for _ in xrange(ctx.num_of_replicas_per_host):
# Note: input_fn is only called once at host 0 for the first replica.
# The features and labels returned from that invocation are
# broadcasted to other replicas(including the replicas on other
# hosts).
if flattened_inputs is None:
features, labels = inputs.features_and_labels() # Calls get_next()
signals = inputs.signals()
inputs_structure_recorder.validate_and_record_structure(
features, labels)
flattened_inputs = (
inputs_structure_recorder.flatten_features_and_labels(
features, labels, signals))
broadcasted_inputs.append(flattened_inputs)
infeed_queue = tpu_feed.InfeedQueue(
number_of_tuple_elements=len(broadcasted_inputs[0]))
captured_infeed_queue.capture(infeed_queue)
enqueue_ops = infeed_queue.generate_enqueue_ops(
broadcasted_inputs,
tpu_ordinal_function=tpu_ordinal_function_impl,
placement_function=device_function_impl)
if signals is None:
return enqueue_ops
else:
return {
'ops': enqueue_ops,
'signals': signals,
}
return enqueue_ops_fn, captured_infeed_queue, dataset_initializer
class _InputPipeline(object):
"""`_InputPipeline` handles invoking `input_fn` and piping to infeed queue.
`_InputPipeline` abstracts the per-core/per-host `input_fn` invocation from
call site. To be precise, based on the configuration in
`_InternalTPUContext`, it invokes `input_fn` for all cores (usually
multi-host TPU training) or for one host (usually for single-host TPU
evaluation), and sends all `features` and `labels` returned by `input_fn` to
TPU infeed. For per-core invocation, `features` and `labels` are piped to
infeed directly, one tuple for each core. For per-host invocation, `features`
and `labels` are split at host (with respect to `batch_axis`) and piped to all
cores accordingly.
In addition, flatten/unflatten are handled by `_InputPipeline` also. Model
inputs returned by the `input_fn` can have one of the following forms:
1. features
2. (features, labels)
3. ((arbitrarily nested structure of features), labels)
Internally, form 1 is reformed to `(features, None)` as features and labels
are passed separately to underlying methods. For TPU training, TPUEstimator
may expect multiple `features` and `labels` tuples one for each core.
TPUEstimator allows various different structures for inputs (namely `features`
and `labels`). Both `features` and `labels` can be any nested sturcture
supported by TF nest (namely, dict, tuples, namedtuples or any nested
structure of such of Tensors). `labels` could be `None` as well.
These are flattened before they are passed to the infeed/outfeed library
as that expectes flattend lists.
"""
class InputsStructureRecorder(object):
"""The recorder to record inputs structure."""
def __init__(self, input_partition_dims=None):
# Holds the structure of inputs
self._feature_structure = {}
self._flattened_input_dims = None
if input_partition_dims:
# This should have been validated in TPUConfig.
assert len(input_partition_dims) <= 2, 'must have 1 or 2 elements.'
if len(input_partition_dims) == 2:
self._feature_dims, self._label_dims = input_partition_dims
else:
self._feature_dims = input_partition_dims[0]
self._label_dims = None
assert self._feature_dims is not None, ('input_partition_dims[0] must '
'not be None')
else:
self._feature_dims = None
self._label_dims = None
# Internal state.
self._initialized = False
@property
def flattened_input_dims(self):
assert self._initialized, 'InputsStructureRecorder is not initialized.'
return self._flattened_input_dims
def has_labels(self):
return 'labels' in self._feature_structure
def _flatten_input_dims(self, feature_dims, feature_dims_names, label_dims,
label_dims_names, label_names, has_labels):
"""Flatten input dims with the same order as flattened input tensors."""
flattened_input_dims = []
if feature_dims_names:
# We need a fixed ordering for matching the tensors in features.
flattened_input_dims.extend(
[feature_dims[name] for name in feature_dims_names])
else:
flattened_input_dims.append(feature_dims)
if label_dims_names:
# We need a fixed ordering for matching the tensors in labels.
flattened_input_dims.extend(
[label_dims[name] for name in label_dims_names])
else:
if label_names:
num_tensors_in_label = len(label_names)
else:
num_tensors_in_label = int(has_labels)
# Setting `None` in input_partition_dims[1] will apply `None` to
# all the tensors in labels, regardless of internal structure.
flattened_input_dims.extend([label_dims] * num_tensors_in_label)
return flattened_input_dims
def validate_and_record_structure(self, features, labels):
"""Validates and records the structure of `features` and `labels`."""
# Extract structure.
has_labels = labels is not None
feature_names = _extract_key_names(features)
label_names = _extract_key_names(labels)
if not self._initialized:
# Record structure.
self._initialized = True
if self._feature_dims is not None:
feature_dims_names = _extract_key_names(self._feature_dims)
if feature_dims_names != feature_names:
raise ValueError(
'TPUConfig.input_partition_dims[0] mismatched feature'
' keys. Expected {}, got {}'.format(feature_names,
feature_dims_names))
label_dims_names = _extract_key_names(self._label_dims)
if self._label_dims is not None and label_dims_names != label_names:
raise ValueError(
'TPUConfig.input_partition_dims[1] mismatched label'
' keys. Expected {}, got {}'.format(label_names,
label_dims_names))
self._flattened_input_dims = self._flatten_input_dims(
self._feature_dims, feature_dims_names, self._label_dims,
label_dims_names, label_names, has_labels)
def flatten_features_and_labels(self, features, labels, signals=None):
"""Flattens the `features` and `labels` to a single tensor list."""
self._feature_structure['features'] = features
if labels is not None:
self._feature_structure['labels'] = labels
if signals is not None:
self._feature_structure['signals'] = signals
return data_nest.flatten(self._feature_structure)
def unflatten_features_and_labels(self, flattened_inputs):
"""Restores the flattened inputs to original features and labels form.
Args:
flattened_inputs: Flattened inputs for each shard.
Returns:
A tuple of (`features`, `labels`), where `labels` could be None.
Each one, if present, should have identical structure (single tensor vs
dict) as the one returned by input_fn.
Raises:
ValueError: If the number of expected tensors from `flattened_inputs`
mismatches the recorded structure.
"""
unflattened_inputs = data_nest.pack_sequence_as(self._feature_structure,
flattened_inputs)
return _Inputs(
unflattened_inputs['features'],
unflattened_inputs.get('labels'),
signals=unflattened_inputs.get('signals'))
def __init__(self, input_fn, batch_axis, ctx):
"""Constructor.
Args:
input_fn: input fn for train or eval.
batch_axis: A python tuple of int values describing how each tensor
produced by the Estimator `input_fn` should be split across the TPU
compute shards.
ctx: A `_InternalTPUContext` instance with mode.
Raises:
ValueError: If both `sharded_features` and `num_cores` are `None`.
"""
self._inputs_structure_recorder = _InputPipeline.InputsStructureRecorder(
ctx.input_partition_dims)
self._sharded_per_core = ctx.is_input_sharded_per_core()
self._input_fn = input_fn
self._infeed_queue = None
self._ctx = ctx
self._batch_axis = batch_axis
def generate_infeed_enqueue_ops_and_dequeue_fn(self):
"""Generates infeed enqueue ops and dequeue_fn."""
# While tf.while_loop is called, the body function, which invokes
# `enqueue_fn` passed in, is called to construct the graph. So, input_fn
# structure is recorded.
enqueue_ops, all_hooks, run_infeed_loop_on_coordinator = (
self._invoke_input_fn_and_record_structure())
self._validate_input_pipeline()
def dequeue_fn():
"""dequeue_fn is used by TPU to retrieve the tensors."""
# In the model-parallel case, both the host-side and device-side
# computations must agree on the core on which infeed takes place. We
# choose to perform infeed on logical core 0 of each replica.
values = self._infeed_queue.generate_dequeue_op(tpu_device=0)
# The unflatten process uses the structure information recorded above.
return self._inputs_structure_recorder.unflatten_features_and_labels(
values)
return (enqueue_ops, dequeue_fn, all_hooks, run_infeed_loop_on_coordinator)
def _invoke_input_fn_and_record_structure(self):
"""Deploys the input pipeline and record input structure."""
enqueue_ops = []
infeed_queues = []
all_dataset_initializers = []
num_hosts = self._ctx.num_hosts
tpu_host_placement_fn = self._ctx.tpu_host_placement_function
run_infeed_loop_on_coordinator = True
if self._sharded_per_core:
# Per-Core input pipeline deployment.
# Invoke input pipeline for each core and placed on the corresponding
# host.
for host_id in range(num_hosts):
host_device = tpu_host_placement_fn(host_id=host_id)
with ops.device(host_device):
with ops.name_scope('input_pipeline_task%d' % (host_id)):
enqueue_ops_fn, captured_infeed_queue = (
generate_per_core_enqueue_ops_fn_for_host(
self._ctx, self._input_fn, self._inputs_structure_recorder,
host_device, host_id))
if _WRAP_INPUT_FN_INTO_WHILE_LOOP:
run_infeed_loop_on_coordinator = False
enqueue_ops.append(
_wrap_computation_in_while_loop(
device=host_device, op_fn=enqueue_ops_fn))
else:
enqueue_ops.append(enqueue_ops_fn())
# Infeed_queue_getter must be called after enqueue_ops_fn is called.
infeed_queues.append(captured_infeed_queue.get())
elif self._ctx.is_input_broadcast_with_iterators():
# Only calls input_fn in host 0.
host_device = tpu_host_placement_fn(host_id=0)
enqueue_ops_fn, captured_infeed_queue, dataset_initializer = (
generate_broadcast_enqueue_ops_fn(self._ctx, self._input_fn,
self._inputs_structure_recorder,
num_hosts))
if dataset_initializer:
all_dataset_initializers.append(dataset_initializer)
run_infeed_loop_on_coordinator = False
wrap_fn = (
_wrap_computation_in_while_loop
if self._ctx.mode != model_fn_lib.ModeKeys.PREDICT else
_wrap_computation_in_while_loop_with_stopping_signals)
enqueue_ops.append(wrap_fn(device=host_device, op_fn=enqueue_ops_fn))
else:
enqueue_ops.append(enqueue_ops_fn())
infeed_queues.append(captured_infeed_queue.get())
else:
for host_id in range(num_hosts):
host_device = tpu_host_placement_fn(host_id=host_id)
with ops.device(host_device):
with ops.name_scope('input_pipeline_task%d' % (host_id)):
if self._ctx.is_input_per_host_with_iterators():
enqueue_ops_fn, captured_infeed_queue, dataset_initializer = (
generate_per_host_v2_enqueue_ops_fn_for_host(
self._ctx, self._input_fn,
self._inputs_structure_recorder, host_device, host_id))
else:
enqueue_ops_fn, captured_infeed_queue, dataset_initializer = (
generate_per_host_enqueue_ops_fn_for_host(
self._ctx, self._input_fn,
self._inputs_structure_recorder, self._batch_axis,
host_device, host_id))
# NOTE(xiejw): We dispatch here based on the return type of the
# users `input_fn`.
#
# 1. If input_fn returns a Dataset instance, we initialize the
# iterator outside of tf.while_loop, and call the iterator.get_next
# inside tf.while_loop. This should be always safe.
#
# 2. If input_fn returns (features, labels), it is too late to wrap
# them inside tf.while_loop, as resource initialization cannot be
# handled in TF control flow properly. In this case, we will use
# python loop to enqueue the data into TPU system. This may be
# slow compared to the previous case.
if dataset_initializer:
all_dataset_initializers.append(dataset_initializer)
run_infeed_loop_on_coordinator = False
wrap_fn = (
_wrap_computation_in_while_loop
if self._ctx.mode != model_fn_lib.ModeKeys.PREDICT else
_wrap_computation_in_while_loop_with_stopping_signals)
enqueue_ops.append(
wrap_fn(device=host_device, op_fn=enqueue_ops_fn))
else:
enqueue_ops.append(enqueue_ops_fn())
infeed_queues.append(captured_infeed_queue.get())
# infeed_queue is used to generate dequeue ops. The only thing it uses for
# dequeue is dtypes and types. So, any one can be used. Here, grab the
# first one.
self._infeed_queue = infeed_queues[0]
return enqueue_ops, [
util_lib.MultiHostDatasetInitializerHook(all_dataset_initializers)
], run_infeed_loop_on_coordinator
def _validate_input_pipeline(self):
"""Validates the input pipeline.
Perform some sanity checks to log user friendly information. We should
error out to give users better error message. But, if
_WRAP_INPUT_FN_INTO_WHILE_LOOP is False (legacy behavior), we cannot break
user code, so, log a warning.
Raises:
RuntimeError: If the validation failed.
"""
if ops.get_default_graph().get_collection(ops.GraphKeys.QUEUE_RUNNERS):
err_msg = ('Input pipeline contains one or more QueueRunners. '
'It could be slow and not scalable. Please consider '
'converting your input pipeline to use `tf.data` instead (see '
'https://www.tensorflow.org/guide/datasets for '
'instructions.')
if _WRAP_INPUT_FN_INTO_WHILE_LOOP:
raise RuntimeError(err_msg)
else:
logging.warn(err_msg)
class _ModelFnWrapper(object):
"""A `model_fn` wrapper.
This makes calling model_fn on CPU and TPU easier and more consistent and
performs necessary check and mutation required by TPU training and evaluation.
In addition, this wrapper manages converting the `model_fn` to a single TPU
train and eval step.
"""
def __init__(self, model_fn, train_cache_fn, eval_cache_fn, config, params, ctx):
self._model_fn = model_fn
self._train_cache_fn = train_cache_fn
self._eval_cache_fn = eval_cache_fn
self._config = config
self._params = params
self._ctx = ctx
def call_without_tpu(self, features, labels, is_export_mode):
return self._call_model_fn(features, labels, is_export_mode=is_export_mode)
def convert_to_single_tpu_train_step(self, dequeue_fn):
"""Converts user provided model_fn` as a single train step on TPU.
The user provided `model_fn` takes input tuple
(features, labels) and produces the EstimatorSpec with train_op and loss for
train `mode`. This usually represents a single train computation on CPU.
For TPU training, a train (computation) step is first wrapped in a
tf.while_loop control flow to repeat for many times and then replicated to
all TPU shards. Besides the input should be taken from TPU infeed rather
than input pipeline (input_fn) directly. To fit TPU loop and replicate
pattern, the original train computation should be reformed, which is the
returned `train_step`.
Args:
dequeue_fn: The function to retrieve inputs, features and labels, from TPU
infeed dequeue channel.
Returns:
A tuple of train_fn, host_calls, and captured scaffold_fn. The train_fn
representing the train step for TPU.
"""
host_call = _OutfeedHostCall(self._ctx)
captured_scaffold_fn = _CapturedObject()
captured_training_hooks = _CapturedObject()
def train_step(loss, *cache):
"""Training step function for use inside a while loop."""
del loss # unused; required in function signature.
inputs = dequeue_fn()
features, labels = inputs.features_and_labels()
# Consume the current cache
estimator_spec = self._verify_estimator_spec(
self._call_model_fn(features, labels, cache=cache))
# Retrieve the new returned cache
"""
`cache` consists of a list of tensors, potentially empty (of length 0)
"""
cache = estimator_spec.cache
loss, train_op = estimator_spec.loss, estimator_spec.train_op
if isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access
captured_scaffold_fn.capture(estimator_spec.scaffold_fn)
else:
captured_scaffold_fn.capture(None)
captured_training_hooks.capture(estimator_spec.training_hooks)
tracing_ops = []
if tensor_tracer.TensorTracer.is_enabled():
tt = tensor_tracer.TensorTracer()
loss, tracing_ops = tt.trace_tpu(ops.get_default_graph(), loss,
self._ctx.num_replicas)
# We must run train_op to update the variables prior to running the
# outfeed.
with ops.control_dependencies([train_op]+tracing_ops):
host_call_outfeed_ops = []
if (isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec) # pylint: disable=protected-access
and estimator_spec.host_call is not None):
host_call.record({'host_call': estimator_spec.host_call})
host_call_outfeed_ops = host_call.create_enqueue_op()
with ops.control_dependencies(host_call_outfeed_ops):
return [array_ops.identity(loss)] + cache
return (train_step, host_call, captured_scaffold_fn,
captured_training_hooks)
def convert_to_single_tpu_eval_step(self, dequeue_fn):
"""Converts user provided model_fn` as a single eval step on TPU.
Similar to training, the user provided `model_fn` takes input tuple
(features, labels) and produces the TPUEstimatorSpec with eval_metrics for
eval `mode`. This usually represents a single evaluation computation on CPU.
For TPU evaluation, a eval (computation) step is first wrapped in a
tf.while_loop control flow to repeat for many times and then replicated to
all TPU shards. Besides the input and output are slightly different. Input,
features and labels, should be taken from TPU infeed rather than input
pipeline (input_fn) directly. Output is managed in two stages. First, the
model outputs as the result of evaluation computation, usually model logits,
should be transferred from TPU system to CPU. Then, all model outputs are
concatenated first on CPU and sent to the metric_fn for metrics computation.
To fit TPU evaluation pattern, the original eval computation should be
reformed, which is the returned `eval_step`.
Args:
dequeue_fn: The function to retrieve inputs, features and labels, from TPU
infeed dequeue channel.
Returns:
A tuple of eval_fn, host_calls, and captured scaffold_fn. The eval_fn
representing the eval step for TPU.
"""
host_calls = _OutfeedHostCall(self._ctx)
captured_scaffold_fn = _CapturedObject()
captured_eval_hooks = _CapturedObject()
def eval_step(total_loss, *cache):
"""Evaluation step function for use inside a while loop."""
inputs = dequeue_fn()
features, labels = inputs.features_and_labels()
# Consume the current cache
tpu_estimator_spec = self._call_model_fn(features, labels, cache=cache)
if not isinstance(tpu_estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access
raise RuntimeError(
'estimator_spec used by TPU evaluation must have type'
'`TPUEstimatorSpec`. Got {}'.format(type(tpu_estimator_spec)))
# Retrieve the new returned cache
cache = tpu_estimator_spec.cache
loss = tpu_estimator_spec.loss
captured_scaffold_fn.capture(tpu_estimator_spec.scaffold_fn)
captured_eval_hooks.capture(tpu_estimator_spec.evaluation_hooks)
to_record = {}
if tpu_estimator_spec.eval_metrics:
to_record['eval_metrics'] = tpu_estimator_spec.eval_metrics
if tpu_estimator_spec.host_call is not None:
# We assume that evaluate won't update global step, so we don't wrap
# this host_call.
to_record['host_call'] = tpu_estimator_spec.host_call
host_calls.record(to_record)
with ops.control_dependencies(host_calls.create_enqueue_op()):
return [math_ops.add(total_loss, loss)] + cache
return eval_step, host_calls, captured_scaffold_fn, captured_eval_hooks
def convert_to_single_tpu_predict_step(self, dequeue_fn):
"""Converts user provided model_fn` as a single predict step on TPU.
Args:
dequeue_fn: The function to retrieve inputs, features and labels, from TPU
infeed dequeue channel.
Returns:
A tuple of predict_fn, host_calls, and captured scaffold_fn. The
predict_fn representing the predict step for TPU.
"""
host_calls = _OutfeedHostCall(self._ctx)
captured_scaffold_fn = _CapturedObject()
captured_predict_hooks = _CapturedObject()
def predict_step(unused_scalar_stopping_signal):
"""Evaluation step function for use inside a while loop."""
inputs = dequeue_fn()
features, labels = inputs.features_and_labels()
stopping_signals = inputs.signals()
assert stopping_signals is not None, (
'Internal Error: `signals` is missing.')
tpu_estimator_spec = self._call_model_fn(
features, labels, is_export_mode=False)
if not isinstance(tpu_estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access
raise RuntimeError(
'estimator_spec used by TPU prediction must have type'
'`TPUEstimatorSpec`. Got {}'.format(type(tpu_estimator_spec)))
self._verify_tpu_spec_predictions(tpu_estimator_spec.predictions)
captured_scaffold_fn.capture(tpu_estimator_spec.scaffold_fn)
captured_predict_hooks.capture(tpu_estimator_spec.prediction_hooks)
to_record = {}
identity_fn = lambda **kwargs: kwargs
to_record['predictions'] = [identity_fn, tpu_estimator_spec.predictions]
to_record['signals'] = [identity_fn, stopping_signals]
if tpu_estimator_spec.host_call is not None:
to_record['host_call'] = tpu_estimator_spec.host_call
host_calls.record(to_record)
with ops.control_dependencies(host_calls.create_enqueue_op()):
return _StopSignals.as_scalar_stopping_signal(stopping_signals)
return (predict_step, host_calls, captured_scaffold_fn,
captured_predict_hooks)
def _verify_tpu_spec_predictions(self, predictions):
"""Validates TPUEstimatorSpec.predictions dict."""
# TODO(xiejw): Adds validation for prediction dictionrary.
# TODO(xiejw): Adds support for single tensor as predictions.
if not isinstance(predictions, dict):
raise TypeError('TPUEstimatorSpec.predictions must be dict of Tensors.')
for (key, tensor) in predictions.items():
if tensor.shape.dims[0].value is None:
raise ValueError(
'The tensor with key ({}) in TPUEstimatorSpec.predictions has '
'dynamic shape (should be static). Tensor: {}'.format(key, tensor))
return predictions
def _validate_model_features_and_labels(self, features, labels,
is_export_mode):
"""Validates that the features and labels for the model function are valid.
A valid features/labels object is the one with:
- Type: A tensor or any nested structure of tensors supported by TF nest,
namely nested dictionary, tuple, namedtuple, or sequence of tensors.
- Static shape if is_export_mode is False.
Args:
features: the features that would be input to the model function.
labels: the labels that would be input to the model function.
is_export_mode: boolean value specifying if in export mode.
Raises:
TypeError: If features/labels are not of the correct type.
ValueError: If features/labels have dynamic shape.
"""
def validate(obj, obj_name):
"""Helper validate function."""
if is_export_mode or self._ctx.is_running_on_cpu(is_export_mode):
return
if isinstance(obj, ops.Tensor):
if not obj.get_shape().is_fully_defined():
raise ValueError(
'The {} to the model returned by input_fn must have static shape.'
' Tensor: {}'.format(obj_name, obj))
else:
for tensor in data_nest.flatten(obj):
if not tensor.get_shape().is_fully_defined():
raise ValueError(
('The {} to the model returned by input_fn must have static '
'shape. Tensor: {}').format(obj_name, tensor))
validate(features, 'features')
if labels is not None:
validate(labels, 'labels')
def _call_model_fn(self, features, labels, cache=None, is_export_mode=False):
"""Calls the model_fn with required parameters."""
self._validate_model_features_and_labels(features, labels, is_export_mode)
model_fn_args = function_utils.fn_args(self._model_fn)
kwargs = {}
# Makes deep copy with `config` and params` in case user mutates them.
config = copy.deepcopy(self._config)
params = copy.deepcopy(self._params)
if 'labels' in model_fn_args:
kwargs['labels'] = labels
elif labels is not None:
raise ValueError(
'model_fn does not take labels, but input_fn returns labels.')
if 'mode' in model_fn_args:
kwargs['mode'] = self._ctx.mode
if 'config' in model_fn_args:
kwargs['config'] = config
if 'params' in model_fn_args:
kwargs['params'] = params
if cache is not None:
params['cache'] = cache
if 'params' not in model_fn_args:
raise ValueError('model_fn ({}) does not include params argument, '
'required by TPUEstimator to pass batch size as '
'params[\'batch_size\']'.format(self._model_fn))
if is_export_mode:
batch_size_for_model_fn = None
else:
batch_size_for_model_fn = self._ctx.batch_size_for_model_fn
if batch_size_for_model_fn is not None:
_add_item_to_params(params, _BATCH_SIZE_KEY, batch_size_for_model_fn)
running_on_cpu = self._ctx.is_running_on_cpu(is_export_mode)
_add_item_to_params(params, _USE_TPU_KEY, not running_on_cpu)
if not running_on_cpu:
user_context = tpu_context.TPUContext(
internal_ctx=self._ctx, call_from_input_fn=False)
_add_item_to_params(params, _CTX_KEY, user_context)
estimator_spec = self._model_fn(features=features, **kwargs)
if (running_on_cpu and
isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec)): # pylint: disable=protected-access
# The estimator_spec will be passed to `Estimator` directly, which expects
# type `EstimatorSpec`.
return estimator_spec.as_estimator_spec()
else:
return estimator_spec
def _verify_estimator_spec(self, estimator_spec):
"""Validates the estimator_spec."""
if isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access
return estimator_spec
err_msg = '{} returned by EstimatorSpec is not supported in TPUEstimator.'
if estimator_spec.training_chief_hooks:
raise ValueError(
err_msg.format('training_chief_hooks') + 'If you want' +
' to pass training hooks, please pass via training_hooks.')
if estimator_spec.scaffold:
logging.warning('EstimatorSpec.Scaffold is ignored by TPU train/eval. '
'Please use TPUEstimatorSpec.')
return estimator_spec
class _OutfeedHostCall(object):
"""Support for `eval_metrics` and `host_call` in TPUEstimatorSpec."""
def __init__(self, ctx):
self._ctx = ctx
self._names = []
# All of these are dictionaries of lists keyed on the name.
self._host_fns = {}
self._tensor_keys = collections.defaultdict(list)
self._tensors = collections.defaultdict(list)
self._tensor_dtypes = collections.defaultdict(list)
self._tensor_shapes = collections.defaultdict(list)
@staticmethod
def validate(host_calls):
"""Validates the `eval_metrics` and `host_call` in `TPUEstimatorSpec`."""
for name, host_call in host_calls.items():
if not isinstance(host_call, (tuple, list)):
raise ValueError('{} should be tuple or list'.format(name))
if len(host_call) != 2:
raise ValueError('{} should have two elements.'.format(name))
if not callable(host_call[0]):
raise TypeError('{}[0] should be callable.'.format(name))
if not isinstance(host_call[1], (tuple, list, dict)):
raise ValueError('{}[1] should be tuple or list, or dict.'.format(name))
if isinstance(host_call[1], (tuple, list)):
fullargspec = tf_inspect.getfullargspec(host_call[0])
fn_args = function_utils.fn_args(host_call[0])
# wrapped_hostcall_with_global_step uses varargs, so we allow that.
if fullargspec.varargs is None and len(host_call[1]) != len(fn_args):
raise RuntimeError(
'In TPUEstimatorSpec.{}, length of tensors {} does not match '
'method args of the function, which takes {}.'.format(
name, len(host_call[1]), len(fn_args)))
@staticmethod
def create_cpu_hostcall(host_calls):
"""Runs on the host_call on CPU instead of TPU when use_tpu=False."""
_OutfeedHostCall.validate(host_calls)
ret = {}
for name, host_call in host_calls.items():
host_fn, tensors = host_call
if isinstance(tensors, (tuple, list)):
ret[name] = host_fn(*tensors)
else:
# Must be dict.
try:
ret[name] = host_fn(**tensors)
except TypeError as e:
logging.warning(
'Exception while calling %s: %s. It is likely the tensors '
'(%s[1]) do not match the '
'function\'s arguments', name, e, name)
raise e
return ret
def record(self, host_calls):
"""Records the host_call structure."""
for name, host_call in host_calls.items():
host_fn, tensor_list_or_dict = host_call
self._names.append(name)
self._host_fns[name] = host_fn
if isinstance(tensor_list_or_dict, dict):
for (key, tensor) in six.iteritems(tensor_list_or_dict):
self._tensor_keys[name].append(key)
self._tensors[name].append(tensor)
self._tensor_dtypes[name].append(tensor.dtype)
self._tensor_shapes[name].append(tensor.shape)
else:
# List or tuple.
self._tensor_keys[name] = None
for tensor in tensor_list_or_dict:
self._tensors[name].append(tensor)
self._tensor_dtypes[name].append(tensor.dtype)
self._tensor_shapes[name].append(tensor.shape)
def create_enqueue_op(self):
"""Create the op to enqueue the recorded host_calls.
Returns:
A list of enqueue ops, which is empty if there are no host calls.
"""
if not self._names:
return []
tensors = []
# TODO(jhseu): Consider deduping tensors.
for name in self._names:
tensors.extend(self._tensors[name])
with ops.device(tpu.core(0)):
return [tpu_ops.outfeed_enqueue_tuple(tensors)]
def create_tpu_hostcall(self):
"""Sends the tensors through outfeed and runs the host_fn on CPU.
The tensors are concatenated along dimension 0 to form a global tensor
across all shards. The concatenated function is passed to the host_fn and
executed on the first host.
Returns:
A dictionary mapping name to the return type of the host_call by that
name.
Raises:
RuntimeError: If outfeed tensor is scalar.
"""
if not self._names:
return {}
ret = {}
# For each i, dequeue_ops[i] is a list containing the tensors from all
# shards. This list is concatenated later.
dequeue_ops = []
tensor_dtypes = []
tensor_shapes = []
for name in self._names:
for _ in self._tensors[name]:
dequeue_ops.append([])
for dtype in self._tensor_dtypes[name]:
tensor_dtypes.append(dtype)
for shape in self._tensor_shapes[name]:
tensor_shapes.append(shape)
# Outfeed ops execute on each replica's first logical core. Note: we must
# constraint it such that we have at most one outfeed dequeue and enqueue
# per replica.
for i in xrange(self._ctx.num_replicas):
host_device, ordinal_id = self._ctx.device_for_replica(i)
with ops.device(host_device):
outfeed_tensors = tpu_ops.outfeed_dequeue_tuple(
dtypes=tensor_dtypes,
shapes=tensor_shapes,
device_ordinal=ordinal_id)
for j, item in enumerate(outfeed_tensors):
dequeue_ops[j].append(item)
# Deconstruct dequeue ops.
dequeue_ops_by_name = {}
pos = 0
for name in self._names:
dequeue_ops_by_name[name] = dequeue_ops[pos:pos +
len(self._tensors[name])]
pos += len(self._tensors[name])
# It is assumed evaluation always happens on single host TPU system. So,
# place all ops on tpu host if possible.
#
# TODO(jhseu): Evaluate whether this is right for summaries.
with ops.device(self._ctx.tpu_host_placement_function(replica_id=0)):
for name in self._names:
dequeue_ops = dequeue_ops_by_name[name]
for i, item in enumerate(dequeue_ops):
if dequeue_ops[i][0].shape.ndims == 0:
raise RuntimeError(
'All tensors outfed from TPU should preserve batch size '
'dimension, but got scalar {}'.format(dequeue_ops[i][0]))
# TODO(xiejw): Allow users to specify the axis for batch size
# dimension.
dequeue_ops[i] = array_ops.concat(dequeue_ops[i], axis=0)
if self._tensor_keys[name] is not None:
# The user-provided eval_metrics[1] is a dict.
dequeue_ops = dict(zip(self._tensor_keys[name], dequeue_ops))
try:
ret[name] = self._host_fns[name](**dequeue_ops)
except TypeError as e:
logging.warning(
'Exception while calling %s: %s. It is likely the tensors '
'(%s[1]) do not match the '
'function\'s arguments', name, e, name)
raise e
else:
ret[name] = self._host_fns[name](*dequeue_ops)
return ret
class _OutfeedHostCallHook(session_run_hook.SessionRunHook):
"""Hook to run host calls when use_tpu=False."""
def __init__(self, tensors):
self._tensors = tensors
def begin(self):
# We duplicate this code from the TPUInfeedOutfeedSessionHook rather than
# create a separate hook to guarantee execution order, because summaries
# need to be initialized before the outfeed thread starts.
# TODO(jhseu): Make a wrapper hook instead?
self._init_ops = contrib_summary.summary_writer_initializer_op()
# Get all the writer resources from the initializer, so we know what to
# flush.
self._finalize_ops = []
for op in self._init_ops:
self._finalize_ops.append(contrib_summary.flush(writer=op.inputs[0]))
def after_create_session(self, session, coord):
session.run(self._init_ops)
def before_run(self, run_context):
return basic_session_run_hooks.SessionRunArgs(self._tensors)
def end(self, session):
session.run(self._finalize_ops)
class ExamplesPerSecondHook(basic_session_run_hooks.StepCounterHook):
"""Calculate and report global_step/sec and examples/sec during runtime."""
def __init__(self,
batch_size,
every_n_steps=100,
every_n_secs=None,
output_dir=None,
summary_writer=None):
self._batch_size = batch_size
super(ExamplesPerSecondHook, self).__init__(
every_n_steps=every_n_steps,
every_n_secs=every_n_secs,
output_dir=output_dir,
summary_writer=summary_writer)
def _log_and_record(self, elapsed_steps, elapsed_time, global_step):
global_step_per_sec = elapsed_steps / elapsed_time
examples_per_sec = self._batch_size * global_step_per_sec
if self._summary_writer is not None:
global_step_summary = Summary(value=[
Summary.Value(tag='global_step/sec', simple_value=global_step_per_sec)
])
example_summary = Summary(value=[
Summary.Value(tag='examples/sec', simple_value=examples_per_sec)
])
self._summary_writer.add_summary(global_step_summary, global_step)
self._summary_writer.add_summary(example_summary, global_step)
logging.info('global_step/sec: %g', global_step_per_sec)
logging.info('examples/sec: %g', examples_per_sec)
class InstallSignalHandlerHook(session_run_hook.SessionRunHook):
"""Change SIGINT (CTRL^C) handler to force quit the process.
The default behavior often results in hanging processes.
The original handler is restored after training/evaluation.
"""
def __init__(self):
self._signal_fn = signal.getsignal(signal.SIGINT)
def before_run(self, run_context):
signal.signal(signal.SIGINT, signal.SIG_DFL)
def end(self, session):
signal.signal(signal.SIGINT, self._signal_fn)
class TPUEstimator(estimator_lib.Estimator):
"""Estimator with TPU support.
TPUEstimator also supports training on CPU and GPU. You don't need to define
a separate `tf.estimator.Estimator`.
TPUEstimator handles many of the details of running on TPU devices, such as
replicating inputs and models for each core, and returning to host
periodically to run hooks.
TPUEstimator transforms a global batch size in params to a per-shard batch
size when calling the `input_fn` and `model_fn`. Users should specify
global batch size in constructor, and then get the batch size for each shard
in `input_fn` and `model_fn` by `params['batch_size']`.
- For training, `model_fn` gets per-core batch size; `input_fn` may get
per-core or per-host batch size depending on `per_host_input_for_training`
in `TPUConfig` (See docstring for TPUConfig for details).
- For evaluation and prediction, `model_fn` gets per-core batch size and
`input_fn` get per-host batch size.
Evaluation
==========
`model_fn` should return `TPUEstimatorSpec`, which expects the `eval_metrics`
for TPU evaluation. However, if eval_on_tpu is False, `model_fn` must return
`EstimatorSpec` and the evaluation will execute on CPU or GPU; in this case
the following discussion on TPU evaluation does not apply.
`TPUEstimatorSpec.eval_metrics` is a tuple of `metric_fn` and `tensors`, where
`tensors` could be a list of any nested structure of `Tensor`s (See
`TPUEstimatorSpec` for details). `metric_fn` takes the `tensors` and returns
a dict from metric string name to the result of calling a metric function,
namely a `(metric_tensor, update_op)` tuple.
One can set `use_tpu` to `False` for testing. All training, evaluation, and
predict will be executed on CPU. `input_fn` and `model_fn` will receive
`train_batch_size` or `eval_batch_size` unmodified as `params['batch_size']`.
Current limitations:
--------------------
1. TPU evaluation only works on a single host (one TPU worker) except
BROADCAST mode.
2. `input_fn` for evaluation should **NOT** raise an end-of-input exception
(`OutOfRangeError` or `StopIteration`). And all evaluation steps and all
batches should have the same size.
Example (MNIST):
----------------
```
# The metric Fn which runs on CPU.
def metric_fn(labels, logits):
predictions = tf.argmax(logits, 1)
return {
'accuracy': tf.metrics.precision(
labels=labels, predictions=predictions),
}
# Your model Fn which runs on TPU (eval_metrics is list in this example)
def model_fn(features, labels, mode, config, params):
...
logits = ...
if mode = tf.estimator.ModeKeys.EVAL:
return tpu_estimator.TPUEstimatorSpec(
mode=mode,
loss=loss,
eval_metrics=(metric_fn, [labels, logits]))
# or specify the eval_metrics tensors as dict.
def model_fn(features, labels, mode, config, params):
...
final_layer_output = ...
if mode = tf.estimator.ModeKeys.EVAL:
return tpu_estimator.TPUEstimatorSpec(
mode=mode,
loss=loss,
eval_metrics=(metric_fn, {
'labels': labels,
'logits': final_layer_output,
}))
```
Prediction
==========
Prediction on TPU is an experimental feature to support large batch inference.
It is not designed for latency-critical system. In addition, due to some
usability issues, for prediction with small dataset, CPU `.predict`, i.e.,
creating a new `TPUEstimator` instance with `use_tpu=False`, might be more
convenient.
Note: In contrast to TPU training/evaluation, the `input_fn` for prediction
*should* raise an end-of-input exception (`OutOfRangeError` or
`StopIteration`), which serves as the stopping signal to `TPUEstimator`. To be
precise, the ops created by `input_fn` produce one batch of the data.
The `predict()` API processes one batch at a time. When reaching the end of
the data source, an end-of-input exception should be raised by one of these
operations. The user usually does not need to do this manually. As long as the
dataset is not repeated forever, the `tf.data` API will raise an end-of-input
exception automatically after the last batch has been produced.
Note: Estimator.predict returns a Python generator. Please consume all the
data from the generator so that TPUEstimator can shutdown the TPU system
properly for user.
Current limitations:
--------------------
1. TPU prediction only works on a single host (one TPU worker).
2. `input_fn` must return a `Dataset` instance rather than `features`. In
fact, .train() and .evaluate() also support Dataset as return value.
Example (MNIST):
----------------
```
height = 32
width = 32
total_examples = 100
def predict_input_fn(params):
batch_size = params['batch_size']
images = tf.random_uniform(
[total_examples, height, width, 3], minval=-1, maxval=1)
dataset = tf.data.Dataset.from_tensor_slices(images)
dataset = dataset.map(lambda images: {'image': images})
dataset = dataset.batch(batch_size)
return dataset
def model_fn(features, labels, params, mode):
# Generate predictions, called 'output', from features['image']
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
predictions={
'predictions': output,
'is_padding': features['is_padding']
})
tpu_est = TPUEstimator(
model_fn=model_fn,
...,
predict_batch_size=16)
# Fully consume the generator so that TPUEstimator can shutdown the TPU
# system.
for item in tpu_est.predict(input_fn=input_fn):
# Filter out item if the `is_padding` is 1.
# Process the 'predictions'
```
Exporting
=========
`export_savedmodel` exports 2 metagraphs, one with `tag_constants.SERVING`,
and another with `tag_constants.SERVING` and `tag_constants.TPU`.
At serving time, these tags are used to select metagraph to load.
Before running the graph on TPU, TPU system needs to be initialized. If
TensorFlow Serving model-server is used, this is done automatically. If
not, please call `session.run(tpu.initialize_system())`.
`tpu.outside_compilation` can be used to wrap TPU incompatible ops in
`model_fn`.
Example:
----------------
```
def model_fn(features, labels, mode, config, params):
...
logits = ...
export_outputs = {
'logits': export_output_lib.PredictOutput(
{'logits': logits})
}
def host_call(logits):
class_ids = math_ops.argmax(logits)
classes = string_ops.as_string(class_ids)
export_outputs['classes'] =
export_output_lib.ClassificationOutput(classes=classes)
tpu.outside_compilation(host_call, logits)
...
```
"""
def __init__(self,
model_fn=None,
train_cache_fn=None,
eval_cache_fn=None,
model_dir=None,
config=None,
params=None,
use_tpu=True,
train_batch_size=None,
eval_batch_size=None,
predict_batch_size=None,
batch_axis=None,
eval_on_tpu=True,
export_to_tpu=True,
warm_start_from=None):
"""Constructs an `TPUEstimator` instance.
Args:
model_fn: Model function as required by `Estimator` which returns
EstimatorSpec or TPUEstimatorSpec. `training_hooks`, 'evaluation_hooks',
and `prediction_hooks` must not capure any TPU Tensor inside the
model_fn.
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator to
continue training a previously saved model. If `None`, the model_dir in
`config` will be used if set. If both are set, they must be same. If
both are `None`, a temporary directory will be used.
config: An `tpu_config.RunConfig` configuration object. Cannot be `None`.
params: An optional `dict` of hyper parameters that will be passed into
`input_fn` and `model_fn`. Keys are names of parameters, values are
basic python types. There are reserved keys for `TPUEstimator`,
including 'batch_size'.
use_tpu: A bool indicating whether TPU support is enabled. Currently, -
TPU training and evaluation respect this bit, but eval_on_tpu can
override execution of eval. See below. - Predict still happens on CPU.
train_batch_size: An int representing the global training batch size.
TPUEstimator transforms this global batch size to a per-shard batch
size, as params['batch_size'], when calling `input_fn` and `model_fn`.
Cannot be `None` if `use_tpu` is `True`. Must be divisible by total
number of replicas.
eval_batch_size: An int representing evaluation batch size. Must be
divisible by total number of replicas.
predict_batch_size: An int representing the prediction batch size. Must be
divisible by total number of replicas.
batch_axis: A python tuple of int values describing how each tensor
produced by the Estimator `input_fn` should be split across the TPU
compute shards. For example, if your input_fn produced (images, labels)
where the images tensor is in `HWCN` format, your shard dimensions would
be [3, 0], where 3 corresponds to the `N` dimension of your images
Tensor, and 0 corresponds to the dimension along which to split the
labels to match up with the corresponding images. If None is supplied,
and per_host_input_for_training is True, batches will be sharded based
on the major dimension. If tpu_config.per_host_input_for_training is
False or `PER_HOST_V2`, batch_axis is ignored.
eval_on_tpu: If False, evaluation runs on CPU or GPU. In this case, the
model_fn must return `EstimatorSpec` when called with `mode` as `EVAL`.
export_to_tpu: If True, `export_savedmodel()` exports a metagraph for
serving on TPU besides the one on CPU.
warm_start_from: Optional string filepath to a checkpoint or SavedModel to
warm-start from, or a `tf.estimator.WarmStartSettings` object to fully
configure warm-starting. If the string filepath is provided instead of
a `WarmStartSettings`, then all variables are warm-started, and it is
assumed that vocabularies and Tensor names are unchanged.
Raises:
ValueError: `params` has reserved keys already.
"""
if config is None or not isinstance(config, tpu_config.RunConfig):
raise ValueError(
'`config` must be provided with type `tpu_config.RunConfig`')
if params is not None and any(k in params for k in _RESERVED_PARAMS_KEYS):
raise ValueError('{} are reserved keys but existed in params {}.'.format(
_RESERVED_PARAMS_KEYS, params))
if use_tpu:
# Perform some very basic validations. More validations will be found in
# _InternalTPUContext.
if train_batch_size is None:
raise ValueError('`train_batch_size` cannot be `None`')
util_lib.check_positive_integer(train_batch_size, 'train_batch_size')
if (config.tpu_config.per_host_input_for_training is
tpu_config.InputPipelineConfig.PER_SHARD_V1 and
config.tpu_config.num_cores_per_replica):
raise ValueError(
'Model parallelism only supports per host input for training. '
'Please adjust TPURunconfig.per_host_input_for_training.')
if eval_batch_size is not None:
util_lib.check_positive_integer(eval_batch_size, 'eval_batch_size')
if predict_batch_size is not None:
util_lib.check_positive_integer(predict_batch_size,
'predict_batch_size')
# Verifies the model_fn signature according to Estimator framework.
estimator_lib._verify_model_fn_args(model_fn, params) # pylint: disable=protected-access
# We cannot store config and params in this constructor as parent
# constructor might change them, such as assigning a temp dir for
# config.model_dir.
model_function = self._augment_model_fn(
model_fn,
train_cache_fn,
eval_cache_fn,
batch_axis)
# Overwrite log_step_count_steps to disable TensorLoggingHook and
# StepCounterHook from being created in Estimator. TPUEstimator already
# added equivalent hooks in _augment_model_fn above.
self._log_every_n_steps = config.log_step_count_steps
config = config.replace(log_step_count_steps=None)
# Passing non-None params as wrapped model_fn has it.
params = params or {}
super(TPUEstimator, self).__init__(
model_fn=model_function,
model_dir=model_dir,
config=config,
params=params,
warm_start_from=warm_start_from)
self._iterations_per_training_loop = (
self._config.tpu_config.iterations_per_loop)
# All properties passed to _InternalTPUContext are immutable.
# pylint: disable=protected-access
self._ctx = tpu_context._get_tpu_context(
self._config, train_batch_size, eval_batch_size, predict_batch_size,
use_tpu, eval_on_tpu)
self._export_to_tpu = export_to_tpu
self._is_input_fn_invoked = None
self._rendezvous = {}
def _add_meta_graph_for_mode(self,
builder,
input_receiver_fn_map,
checkpoint_path,
save_variables=True,
mode=model_fn_lib.ModeKeys.PREDICT,
export_tags=None,
check_variables=True):
if self._export_to_tpu and mode != model_fn_lib.ModeKeys.PREDICT:
raise NotImplementedError(
'TPUEstimator only handles mode PREDICT for exporting '
'when `export_to_tpu` is `True`; '
'got {}.'.format(mode))
(super(TPUEstimator, self)._add_meta_graph_for_mode(
builder,
input_receiver_fn_map,
checkpoint_path,
save_variables,
mode=mode,
export_tags=export_tags,
check_variables=check_variables))
if self._export_to_tpu:
input_receiver_fn_map = {
_REWRITE_FOR_INFERENCE_MODE: input_receiver_fn_map[mode]
}
export_tags = [tag_constants.SERVING, tag_constants.TPU]
mode = _REWRITE_FOR_INFERENCE_MODE
# See b/110052256 for why `check_variables` is `False`.
(super(TPUEstimator, self)._add_meta_graph_for_mode(
builder,
input_receiver_fn_map,
checkpoint_path,
save_variables=False,
mode=mode,
export_tags=export_tags,
check_variables=False))
def _call_model_fn(self, features, labels, mode, config):
if mode == _REWRITE_FOR_INFERENCE_MODE:
return self._call_model_fn_for_inference(features, labels, mode, config)
else:
return super(TPUEstimator, self)._call_model_fn(features, labels, mode,
config)
def _call_model_fn_for_inference(self, features, labels, mode, config):
"""Wraps `_call_model_fn` for `export_savedmodel`."""
if mode != _REWRITE_FOR_INFERENCE_MODE:
raise ValueError('mode must be {}; '
'got {}.'.format(_REWRITE_FOR_INFERENCE_MODE, mode))
capture = _CapturedObject()
def computation():
"""Compute tpu tensors used in export_outputs.
Passed to rewrite_for_inference so that model_fn will be called under
the rewriting contexts. Only tpu tensors are returned, but export_outputs
and scaffold are captured.
Returns:
A list of Tensors used in export_outputs and not marked for
outside_compilation.
"""
# We should only call model fn once and it should be inside `computation`
# so that building the graph will happen under `rewrite_for_inference`.
mode = model_fn_lib.ModeKeys.PREDICT
estimator_spec = self._call_model_fn(features, labels, mode, config)
# We pick the TPU tensors out from `export_output` and later return them
# from `computation` for rewriting.
tensors_dict = collections.OrderedDict(
(k, _export_output_to_tensors(v))
for k, v in six.iteritems(estimator_spec.export_outputs))
tensors = nest.flatten(tensors_dict)
tpu_tensors = [t for t in tensors if t is not None]
# We cannot return anything other than `tpu_tensors` here so we capture
# the rest for later use.
capture.capture((estimator_spec, tensors_dict, tensors))
return tpu_tensors
tpu_tensors_on_cpu = tpu.rewrite_for_inference(computation)
estimator_spec, tensors_dict, tensors = capture.get()
# Reconstruct `tensors`, but with `tpu_tensors` replaced with
# `tpu_tensors_on_cpu`.
new_tensors = []
for t in tensors:
if t is None:
new_tensors.append(None)
else:
new_tensors.append(tpu_tensors_on_cpu.pop(0))
# Reconstruct `tensors_dict`.
new_tensors_dict = nest.pack_sequence_as(tensors_dict, new_tensors)
# Reconstruct `export_outputs`.
export_outputs = estimator_spec.export_outputs
new_export_outputs = collections.OrderedDict(
(k, _clone_export_output_with_tensors(export_outputs[k], v))
for k, v in six.iteritems(new_tensors_dict))
return estimator_spec._replace(export_outputs=new_export_outputs)
def _create_global_step(self, graph):
"""Creates a global step suitable for TPUs.
Args:
graph: The graph in which to create the global step.
Returns:
A global step `Tensor`.
Raises:
ValueError: if the global step tensor is already defined.
"""
return _create_global_step(graph)
def _convert_train_steps_to_hooks(self, steps, max_steps):
with self._ctx.with_mode(model_fn_lib.ModeKeys.TRAIN) as ctx:
if ctx.is_running_on_cpu():
return super(TPUEstimator, self)._convert_train_steps_to_hooks(
steps, max_steps)
# On TPU.
if steps is None and max_steps is None:
raise ValueError(
'For TPU training, one of `steps` or `max_steps` must be set. '
'Cannot be both `None`.')
# Estimator.train has explicit positiveness check.
if steps is not None:
util_lib.check_positive_integer(steps, 'Train steps')
if max_steps is not None:
util_lib.check_positive_integer(max_steps, 'Train max_steps')
return [
_TPUStopAtStepHook(self._iterations_per_training_loop, steps, max_steps)
]
def _convert_eval_steps_to_hooks(self, steps):
with self._ctx.with_mode(model_fn_lib.ModeKeys.EVAL) as ctx:
if ctx.is_running_on_cpu():
return super(TPUEstimator, self)._convert_eval_steps_to_hooks(steps)
if steps is None:
raise ValueError('Evaluate `steps` must be set on TPU. Cannot be `None`.')
util_lib.check_positive_integer(steps, 'Eval steps')
return [
evaluation._StopAfterNEvalsHook( # pylint: disable=protected-access
num_evals=steps),
_SetEvalIterationsHook(steps)
]
def _call_input_fn(self, input_fn, mode):
"""Calls the input function.
Args:
input_fn: The input function.
mode: ModeKeys
Returns:
In TPU mode, returns an input_fn to be called later in model_fn.
Otherwise, calls the input_fn and returns either fatures or
(features, labels).
Raises:
ValueError: if input_fn takes invalid arguments or does not have `params`.
"""
input_fn_args = function_utils.fn_args(input_fn)
config = self.config # a deep copy.
kwargs = {}
if 'params' in input_fn_args:
kwargs['params'] = self.params # a deep copy.
else:
raise ValueError('input_fn ({}) does not include params argument, '
'required by TPUEstimator to pass batch size as '
'params["batch_size"]'.format(input_fn))
if 'config' in input_fn_args:
kwargs['config'] = config
if 'mode' in input_fn_args:
kwargs['mode'] = mode
# Records the fact input_fn has been invoked.
self._is_input_fn_invoked = True
with self._ctx.with_mode(mode) as ctx:
# Setting the batch size in params first. This helps user to have same
# input_fn for use_tpu=True/False.
batch_size_for_input_fn = ctx.batch_size_for_input_fn
if batch_size_for_input_fn is not None:
_add_item_to_params(kwargs['params'], _BATCH_SIZE_KEY,
batch_size_for_input_fn)
# For export_savedmodel, input_fn is never passed to Estimator. So,
# `is_export_mode` must be False.
if ctx.is_running_on_cpu(is_export_mode=False):
with ops.device('/device:CPU:0'):
return input_fn(**kwargs)
# For TPU computation, input_fn should be invoked in a tf.while_loop for
# performance. While constructing the tf.while_loop, the structure of
# inputs returned by the `input_fn` needs to be recorded. The structure
# includes whether features or labels is dict or single Tensor, dict keys,
# tensor shapes, and dtypes. The recorded structure is used to create the
# infeed dequeue ops, which must be wrapped and passed as a Fn, called
# inside the TPU computation, as the TPU computation is wrapped inside a
# tf.while_loop also. So, we either pass input_fn to model_fn or pass
# dequeue_fn to model_fn. Here, `input_fn` is passed directly as
# `features` in `model_fn` signature.
def _input_fn(ctx):
_add_item_to_params(kwargs['params'], _CTX_KEY, ctx)
return input_fn(**kwargs)
return _input_fn
def _validate_features_in_predict_input(self, result):
"""Skip the validation.
For TPUEstimator, we do not need to check the result type. `_InputPipeline`
has stronger check. Parent class's check generates confusing warning msg.
Args:
result: `features` returned by input_fn.
"""
pass
def train(self,
input_fn,
hooks=None,
steps=None,
max_steps=None,
saving_listeners=None):
rendezvous = error_handling.ErrorRendezvous(num_sources=3)
self._rendezvous[model_fn_lib.ModeKeys.TRAIN] = rendezvous
try:
return super(TPUEstimator, self).train(
input_fn=input_fn,
hooks=hooks,
steps=steps,
max_steps=max_steps,
saving_listeners=saving_listeners)
except Exception: # pylint: disable=broad-except
rendezvous.record_error('training_loop', sys.exc_info())
finally:
rendezvous.record_done('training_loop')
rendezvous.raise_errors()
def evaluate(self,
input_fn,
steps=None,
hooks=None,
checkpoint_path=None,
name=None):
rendezvous = error_handling.ErrorRendezvous(num_sources=3)
self._rendezvous[model_fn_lib.ModeKeys.EVAL] = rendezvous
try:
return super(TPUEstimator, self).evaluate(
input_fn,
steps=steps,
hooks=hooks,
checkpoint_path=checkpoint_path,
name=name)
except Exception: # pylint: disable=broad-except
rendezvous.record_error('evaluation_loop', sys.exc_info())
finally:
rendezvous.record_done('evaluation_loop')
rendezvous.raise_errors()
def predict(self,
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True):
rendezvous = error_handling.ErrorRendezvous(num_sources=3)
self._rendezvous[model_fn_lib.ModeKeys.PREDICT] = rendezvous
try:
for result in super(TPUEstimator, self).predict(
input_fn=input_fn,
predict_keys=predict_keys,
hooks=hooks,
checkpoint_path=checkpoint_path,
yield_single_examples=yield_single_examples):
yield result
except Exception: # pylint: disable=broad-except
rendezvous.record_error('prediction_loop', sys.exc_info())
finally:
rendezvous.record_done('prediction_loop')
rendezvous.raise_errors()
rendezvous.record_done('prediction_loop')
rendezvous.raise_errors()
def _augment_model_fn(self, model_fn, train_cache_fn, eval_cache_fn, batch_axis):
"""Returns a new model_fn, which wraps the TPU support."""
def _model_fn(features, labels, mode, config, params):
"""A Estimator `model_fn` for TPUEstimator."""
with self._ctx.with_mode(mode) as ctx:
model_fn_wrapper = _ModelFnWrapper(model_fn, train_cache_fn,
eval_cache_fn, config, params, ctx)
# `input_fn` is called in `train()`, `evaluate()`, and `predict()`,
# but not in `export_savedmodel()`.
if self._is_input_fn_invoked:
is_export_mode = False
else:
is_export_mode = True
# Clear the bit.
self._is_input_fn_invoked = None
# examples_hook is added to training_hooks for both CPU and TPU
# execution.
if self._log_every_n_steps is not None:
examples_hook = ExamplesPerSecondHook(
ctx.global_batch_size,
output_dir=self.model_dir,
every_n_steps=self._log_every_n_steps)
if ctx.is_running_on_cpu(is_export_mode=is_export_mode):
logging.info('Running %s on CPU', mode)
estimator_spec = model_fn_wrapper.call_without_tpu(
features, labels, is_export_mode=is_export_mode)
if self._log_every_n_steps is not None:
estimator_spec = estimator_spec._replace(
training_hooks=estimator_spec.training_hooks + (examples_hook,))
return estimator_spec
assert labels is None, '`labels` passed to `model_fn` must be `None`.'
# TPUEstimator._call_input_fn passes `input_fn` as features to here.
assert callable(features), '`input_fn` is not callable.'
input_fn = features
input_holders = _InputPipeline(input_fn, batch_axis, ctx)
enqueue_ops, dequeue_fn, input_hooks, run_infeed_loop_on_coordinator = (
input_holders.generate_infeed_enqueue_ops_and_dequeue_fn())
graph = ops.get_default_graph()
for enqueue_op in enqueue_ops:
if isinstance(enqueue_op, list):
graph.get_collection_ref(_TPU_ENQUEUE_OPS).extend(enqueue_op)
else:
graph.add_to_collection(_TPU_ENQUEUE_OPS, enqueue_op)
if mode == model_fn_lib.ModeKeys.TRAIN:
compile_op, loss, host_call, scaffold, training_hooks = (
_train_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn))
host_ops = host_call.create_tpu_hostcall()
if host_ops is None:
host_ops = []
shutdown_hooks = []
shutdown_mode = os.environ.get('TF_TPU_GRACEFUL_SHUTDOWN_MODE',
'shutdown_worker')
if shutdown_mode:
if shutdown_mode == 'shutdown_worker':
finalizer_hooks = [
session_support.ShutdownLameWorkers(timeout_ms=60 * 1000),
]
elif shutdown_mode == 'shutdown_computation':
finalizer_hooks = [
session_support.RestartComputation(timeout_ms=60 * 1000),
]
else:
raise ValueError(
'Unknown TF_TPU_GRACEFUL_SHUTDOWN_MODE "%s"' % shutdown_mode)
shutdown_hooks.append(
session_support.GracefulShutdownHook(
checkpoint_prefix=self.model_dir + '/model.ckpt',
on_shutdown_hooks=finalizer_hooks))
with ops.control_dependencies([loss]):
global_step = array_ops.identity(training.get_global_step())
hooks = input_hooks + shutdown_hooks
hooks.extend([
TPUInfeedOutfeedSessionHook(
ctx,
enqueue_ops,
host_ops,
tpu_compile_op=compile_op,
run_infeed_loop_on_coordinator=(
run_infeed_loop_on_coordinator),
rendezvous=self._rendezvous[mode],
master=self._config.master,
session_config=self._session_config,
),
InstallSignalHandlerHook()
])
if self._log_every_n_steps is not None:
logging_hook_frequency = ( # Divide and round up
(self._log_every_n_steps +
self._config.tpu_config.iterations_per_loop - 1) //
self._config.tpu_config.iterations_per_loop)
hooks.append(
training.LoggingTensorHook({
'loss': array_ops.identity(loss),
'step': global_step,
},
every_n_iter=logging_hook_frequency))
examples_hook._set_steps_per_run( # pylint: disable=protected-access
self._config.tpu_config.iterations_per_loop)
hooks.append(examples_hook)
if training_hooks:
hooks.extend(training_hooks)
chief_hooks = []
if (self._config.save_checkpoints_secs or
self._config.save_checkpoints_steps):
checkpoint_hook = training.CheckpointSaverHook(
self.model_dir,
save_secs=self._config.save_checkpoints_secs,
save_steps=self._config.save_checkpoints_steps,
scaffold=scaffold)
checkpoint_hook._set_steps_per_run( # pylint: disable=protected-access
self._config.tpu_config.iterations_per_loop)
chief_hooks.append(checkpoint_hook)
summary.scalar(model_fn_lib.LOSS_METRIC_KEY, loss)
with ops.control_dependencies([loss]):
update_ops = _sync_variables_ops(ctx)
# Validate the TPU training graph to catch basic errors
_validate_tpu_training_graph()
train_op = control_flow_ops.group(*update_ops)
graph.add_to_collection(_TPU_TRAIN_OP, train_op)
return model_fn_lib.EstimatorSpec(
mode,
loss=loss,
training_chief_hooks=chief_hooks,
training_hooks=hooks,
train_op=train_op,
scaffold=scaffold)
if mode == model_fn_lib.ModeKeys.EVAL:
compile_op, total_loss, host_calls, scaffold, eval_hooks = (
_eval_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn))
iterations_per_loop_var = _create_or_get_iterations_per_loop()
mean_loss = math_ops.div(
total_loss,
math_ops.cast(iterations_per_loop_var, dtype=total_loss.dtype))
with ops.control_dependencies([mean_loss]):
# After TPU evaluation computation is done (the mean_loss tensor),
# reads all variables back from TPU and updates the eval step
# counter properly
internal_ops_to_run = _sync_variables_ops(ctx)
internal_ops_to_run.append(
_increase_eval_step_op(iterations_per_loop_var))
host_call_ret = host_calls.create_tpu_hostcall()
eval_metric_ops = {}
eval_update_ops = []
eval_metrics = host_call_ret.get('eval_metrics', {})
if eval_metrics:
# Creates a dummy metric update_op for all metrics. Estimator
# expects all metrics in `eval_metric_ops` have update_op and calls
# them one by one. The real metric update_ops are invoked in a
# separated thread. So, here give Estimator the dummy op for all
# metrics.
with ops.control_dependencies(internal_ops_to_run):
dummy_update_op = control_flow_ops.no_op()
for k, v in eval_metrics.items():
eval_metric_ops[k] = (v[0], dummy_update_op)
eval_update_ops.append(v[1])
else:
# If no eval metrics are passed, create an identity node for the
# loss and add `internal_ops_to_run` to its dependencies. So
# `internal_ops_to_run` can be executed.
with ops.control_dependencies(internal_ops_to_run):
mean_loss = array_ops.identity(mean_loss)
if 'host_call' not in host_call_ret:
host_ops = []
else:
host_ops = host_call_ret['host_call']
hooks = [
TPUInfeedOutfeedSessionHook(
ctx,
enqueue_ops,
eval_update_ops + host_ops,
tpu_compile_op=compile_op,
run_infeed_loop_on_coordinator=(
run_infeed_loop_on_coordinator),
rendezvous=self._rendezvous[mode],
master=self._config.evaluation_master,
session_config=self._session_config,
)] + input_hooks
if eval_hooks:
hooks.extend(eval_hooks)
return model_fn_lib.EstimatorSpec(
mode,
loss=mean_loss,
evaluation_hooks=hooks,
eval_metric_ops=eval_metric_ops,
scaffold=scaffold)
# Predict
assert mode == model_fn_lib.ModeKeys.PREDICT
(compile_op, dummy_predict_op, host_calls,
scaffold, prediction_hooks) = _predict_on_tpu_system(
ctx, model_fn_wrapper, dequeue_fn)
with ops.control_dependencies([dummy_predict_op]):
internal_ops_to_run = _sync_variables_ops(ctx)
with ops.control_dependencies(internal_ops_to_run):
dummy_predict_op = control_flow_ops.no_op()
# In train and evaluation, the main TPU program is passed to monitored
# training session to run. Infeed enqueue and outfeed dequeue are
# executed in side threads. This is not the configuration for
# prediction mode.
#
# For prediction, the Estimator executes the EstimatorSpec.predictions
# directly and yield the element (via generator) to call site. So, the
# outfeed based prediction must be passed to MonitoredSession directly.
# Other parts of the TPU execution are organized as follows.
#
# 1. All outfeed based Tensors must be grouped with predictions Tensors
# to form a single invocation. This avoid the issue we might trigger
# multiple outfeeds incorrectly. To achieve this, `host_call` is
# placed in control_dependencies of `stopping_signals`, and
# `stopping_signals` is passed into _StoppingPredictHook, which sets
# the `stopping_signals` as SessionRunArgs. MonitoredSession merges
# all SessionRunArgs with the fetch in session.run together.
#
# 2. The TPU program (dummy_predict_op) and enqueue_ops (infeed Enqueue)
# are grouped together. They will be launched once and only once in
# side threads and they quit naturally according to the SAME stopping
# condition.
enqueue_ops.append(dummy_predict_op)
host_call_ret = host_calls.create_tpu_hostcall()
if 'host_call' not in host_call_ret:
host_ops = []
else:
host_ops = host_call_ret['host_call']
predictions = host_call_ret['predictions']
_verify_cross_hosts_transfer_size(
predictions,
message=(
'The estimated size for TPUEstimatorSpec.predictions is too '
'large.'))
signals = host_call_ret['signals']
with ops.control_dependencies(host_ops):
host_ops = [] # Empty, we do do not need it anymore.
scalar_stopping_signal = _StopSignals.as_scalar_stopping_signal(
signals)
predictions = _PaddingSignals.slice_tensor_or_dict(
predictions, signals)
hooks = [
_StoppingPredictHook(scalar_stopping_signal),
TPUInfeedOutfeedSessionHookForPrediction(
ctx, enqueue_ops, host_ops, rendezvous=self._rendezvous[mode],
tpu_compile_op=compile_op,
master=self._config.master,
session_config=self._session_config),
] + input_hooks
if prediction_hooks:
hooks.extend(prediction_hooks)
return model_fn_lib.EstimatorSpec(
mode,
prediction_hooks=hooks,
predictions=predictions,
scaffold=scaffold)
return _model_fn
def _export_output_to_tensors(export_output):
"""Get a list of `Tensors` used in `export_output`.
Args:
export_output: an `ExportOutput` object such as `ClassificationOutput`,
`RegressionOutput`, or `PredictOutput`.
Returns:
a list of tensors used in export_output.
Raises:
ValueError: if `export_output` is not one of `ClassificationOutput`,
`RegressionOutput`, or `PredictOutput`.
"""
if isinstance(export_output, export_output_lib.ClassificationOutput):
return [export_output.scores, export_output.classes]
elif isinstance(export_output, export_output_lib.RegressionOutput):
return [export_output.value]
elif isinstance(export_output, export_output_lib.PredictOutput):
return list(export_output.outputs.values())
else:
raise ValueError(
'`export_output` must be have type `ClassificationOutput`, '
'`RegressionOutput`, or `PredictOutput`; got {}.'.format(export_output))
def _clone_export_output_with_tensors(export_output, tensors):
"""Clones `export_output` but with new `tensors`.
Args:
export_output: an `ExportOutput` object such as `ClassificationOutput`,
`RegressionOutput`, or `PredictOutput`.
tensors: a list of `Tensors` used to construct a new `export_output`.
Returns:
A dict similar to `export_output` but with `tensors`.
Raises:
ValueError: if `export_output` is not one of `ClassificationOutput`,
`RegressionOutput`, or `PredictOutput`.
"""
if isinstance(export_output, export_output_lib.ClassificationOutput):
if len(tensors) != 2:
raise ValueError('tensors must be of length 2; '
'got {}.'.format(len(tensors)))
return export_output_lib.ClassificationOutput(*tensors)
elif isinstance(export_output, export_output_lib.RegressionOutput):
if len(tensors) != 1:
raise ValueError('tensors must be of length 1; '
'got {}'.format(len(tensors)))
return export_output_lib.RegressionOutput(*tensors)
elif isinstance(export_output, export_output_lib.PredictOutput):
return export_output_lib.PredictOutput(
dict(zip(export_output.outputs.keys(), tensors)))
else:
raise ValueError(
'`export_output` must be have type `ClassificationOutput`, '
'`RegressionOutput`, or `PredictOutput`; got {}.'.format(export_output))
def _eval_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn):
"""Executes `model_fn_wrapper` multiple times on all TPU shards."""
iterations_per_loop_var = _create_or_get_iterations_per_loop()
(single_tpu_eval_step, host_calls, captured_scaffold_fn, captured_eval_hooks
) = model_fn_wrapper.convert_to_single_tpu_eval_step(dequeue_fn)
def multi_tpu_eval_steps_on_single_shard():
loop_vars = [_ZERO_LOSS]
if model_fn_wrapper._eval_cache_fn is not None:
batch_size = ctx.global_batch_size
num_shards = ctx._config._tpu_config.num_shards
loop_vars += model_fn_wrapper._eval_cache_fn(batch_size // num_shards)
return training_loop.repeat(
iterations_per_loop_var,
single_tpu_eval_step,
loop_vars)
compile_op, ret = tpu.split_compile_and_shard(
multi_tpu_eval_steps_on_single_shard,
inputs=[],
num_shards=ctx.num_replicas,
outputs_from_all_shards=False,
device_assignment=ctx.device_assignment)
loss = ret[0]
scaffold = _get_scaffold(captured_scaffold_fn)
return compile_op, loss, host_calls, scaffold, captured_eval_hooks.get()
def _train_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn):
"""Executes `model_fn_wrapper` multiple times on all TPU shards."""
iterations_per_loop_var = _create_or_get_iterations_per_loop()
(single_tpu_train_step, host_call, captured_scaffold_fn,
captured_training_hooks) = (
model_fn_wrapper.convert_to_single_tpu_train_step(dequeue_fn))
def multi_tpu_train_steps_on_single_shard():
loop_vars = [_INITIAL_LOSS]
if model_fn_wrapper._train_cache_fn is not None:
batch_size = ctx.global_batch_size
num_shards = ctx._config._tpu_config.num_shards
loop_vars += model_fn_wrapper._train_cache_fn(batch_size // num_shards)
return training_loop.repeat(
iterations_per_loop_var,
single_tpu_train_step,
loop_vars)
compile_op, ret = tpu.split_compile_and_shard(
multi_tpu_train_steps_on_single_shard,
inputs=[],
num_shards=ctx.num_replicas,
outputs_from_all_shards=False,
device_assignment=ctx.device_assignment)
loss = ret[0]
scaffold = _get_scaffold(captured_scaffold_fn)
return compile_op, loss, host_call, scaffold, captured_training_hooks.get()
def _predict_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn):
"""Executes `model_fn_wrapper` multiple times on all TPU shards."""
(single_tpu_predict_step, host_calls, captured_scaffold_fn,
captured_predict_hooks
) = model_fn_wrapper.convert_to_single_tpu_predict_step(dequeue_fn)
def multi_tpu_predict_steps_on_single_shard():
def cond(scalar_stopping_signal):
return math_ops.logical_not(
_StopSignals.should_stop(scalar_stopping_signal))
inputs = [_StopSignals.NON_STOPPING_SIGNAL]
outputs = training_loop.while_loop(
cond, single_tpu_predict_step, inputs=inputs, name=b'loop')
return outputs
(compile_op, dummy_predict_op,) = tpu.split_compile_and_shard(
multi_tpu_predict_steps_on_single_shard,
inputs=[],
num_shards=ctx.num_replicas,
outputs_from_all_shards=False,
device_assignment=ctx.device_assignment)
dummy_predict_op = dummy_predict_op[0]
scaffold = _get_scaffold(captured_scaffold_fn)
return (compile_op, dummy_predict_op, host_calls, scaffold,
captured_predict_hooks.get())
def _wrap_computation_in_while_loop(device, op_fn):
"""Wraps the ops generated by `op_fn` in tf.while_loop."""
def computation(i):
with ops.control_dependencies(op_fn()):
return i + 1
iterations_per_loop_var = _create_or_get_iterations_per_loop()
# By setting parallel_iterations=1, the parallel execution in while_loop is
# basically turned off.
with ops.device(device):
iterations = array_ops.identity(iterations_per_loop_var)
return control_flow_ops.while_loop(
lambda i: i < iterations,
computation, [constant_op.constant(0)],
parallel_iterations=1)
def _wrap_computation_in_while_loop_with_stopping_signals(device, op_fn):
"""Wraps the ops generated by `op_fn` in tf.while_loop."""
def cond(scalar_stopping_signal):
return math_ops.logical_not(
_StopSignals.should_stop(scalar_stopping_signal))
def computation(unused_scalar_stopping_signal):
return_value = op_fn()
execute_ops = return_value['ops']
signals = return_value['signals']
with ops.control_dependencies(execute_ops):
return _StopSignals.as_scalar_stopping_signal(signals)
# By setting parallel_iterations=1, the parallel execution in while_loop is
# basically turned off.
with ops.device(device):
return control_flow_ops.while_loop(
cond,
computation, [_StopSignals.NON_STOPPING_SIGNAL],
parallel_iterations=1)
def _validate_tpu_training_graph():
"""Validate graph before running distributed training.
Raises:
ValueError: If the graph seems invalid for running on device
"""
operations = ops.get_default_graph().get_operations()
# Check if there is atleast one CrossReplicaSum operation in the graph
# This should be introduced by using the CrossShardOptimizer wrapper
cross_replica_sum_ops = [
o for o in operations if o.type == _CROSS_REPLICA_SUM_OP
]
if not cross_replica_sum_ops:
raise ValueError(
'CrossShardOptimizer must be used for model training on TPUs.')
class _CapturedObject(object):
"""A placeholder to capture an object.
This is useful when we need to capture a Python object in the Tensorflow
control flow body function and use it outside the control flow.
"""
def __init__(self):
self._object = None
self._captured = False
def capture(self, o):
if self._captured:
raise RuntimeError(
'InternalError: Object can capture only once. Please file bug.')
self._captured = True
self._object = o
def get(self):
if not self._captured:
raise RuntimeError(
'InternalError: Object is not captured properly before `get`. '
'Please file bug.')
return self._object
def _get_scaffold(captured_scaffold_fn):
"""Retrieves the Scaffold from `captured_scaffold_fn`."""
with _CapturingContext(message='Inside scaffold_fn'):
scaffold_fn = captured_scaffold_fn.get()
if scaffold_fn:
scaffold = scaffold_fn()
if scaffold is None:
raise ValueError(
'TPUEstimatorSpec.scaffold_fn returns None, which is not allowed')
else:
scaffold = None
if scaffold:
wrapped_finalize = scaffold.finalize
def _finalize():
with _CapturingContext('Inside Scaffold.finalize'):
wrapped_finalize()
scaffold.finalize = _finalize
return scaffold
class _CapturingContext(control_flow_ops.ControlFlowContext):
"""Tracks references to Tensors defined in TPU replication."""
def __init__(self, message):
control_flow_ops.ControlFlowContext.__init__(self)
self._message = message
def to_control_flow_context_def(self, context_def, export_scope=None):
# pylint: disable=useless-super-delegation
# NOTE(slebedev): the method is required by `ControlFlowContext`.
super(_CapturingContext, self).to_control_flow_context_def(
context_def, export_scope)
def AddOp(self, op): # pylint: disable=invalid-name
for c in op.inputs:
if tpu._TPU_REPLICATE_ATTR in c.op.node_def.attr: # pylint: disable=protected-access
raise ValueError('{}: Op {} depends on TPU computation {}, '
'which is not allowed.'.format(self._message, op, c))
def __enter__(self):
# pylint: disable=protected-access
self._g = ops.get_default_graph()
self._old = self._g._get_control_flow_context()
self._g._set_control_flow_context(self)
# pylint: enable=protected-access
def __exit__(self, _, __, ___): # pylint: disable=invalid-name
self._g._set_control_flow_context(self._old) # pylint: disable=protected-access
class _Inputs(object):
"""A data structure representing the input_fn returned values.
This also supports the returned value from input_fn as `Dataset`.
"""
def __init__(self, features=None, labels=None, dataset=None, signals=None):
if dataset is not None and (features is not None or labels is not None or
signals is not None):
raise RuntimeError('Internal Error: Either (features and labels) or '
'dataset should be provided, not both. Please file '
'bug')
self._features = features
self._labels = labels
self._signals = signals
self._dataset = dataset
self._iterator = None
@staticmethod
def from_input_fn(return_values):
"""Returns an `_Inputs` instance according to `input_fn` return value."""
if isinstance(return_values, dataset_ops.DatasetV2):
dataset = return_values
return _Inputs(dataset=dataset)
features, labels = _Inputs._parse_inputs(return_values)
return _Inputs(features, labels)
@staticmethod
def _parse_inputs(return_values):
if isinstance(return_values, tuple):
features, labels = return_values
else:
features, labels = return_values, None
return features, labels
@property
def is_dataset(self):
"""Returns True if the return value from input_fn is Dataset."""
return self._dataset is not None
def dataset_initializer(self):
"""Returns the dataset's initializer.
The initializer must be run before calling `features_and_labels`.
"""
self._iterator = dataset_ops.make_initializable_iterator(self._dataset)
return self._iterator.initializer
def features_and_labels(self):
"""Gets `features` and `labels`."""
if self.is_dataset:
if self._iterator is None:
raise RuntimeError('Internal error: Must run dataset_initializer '
'before calling features_and_labels(). Please file '
'a bug!')
return _Inputs._parse_inputs(self._iterator.get_next())
return (self._features, self._labels)
def signals(self):
return self._signals
@property
def dataset(self):
return self._dataset
class _InputsWithStoppingSignals(_Inputs):
"""Inputs with `_StopSignals` inserted into the dataset."""
def __init__(self,
dataset,
batch_size,
add_padding=False,
num_invocations_per_step=1):
assert dataset is not None
user_provided_dataset = dataset.map(
_InputsWithStoppingSignals.insert_stopping_signal(
stop=False, batch_size=batch_size, add_padding=add_padding))
if num_invocations_per_step == 1:
final_batch_dataset = dataset.take(1).map(
_InputsWithStoppingSignals.insert_stopping_signal(
stop=True, batch_size=batch_size, add_padding=add_padding))
else:
# We append (2 * num_invocations_per_step - 1) batches for exhausting the
# user_provided_dataset and stop properly.
# For example, if num_invocations_per_step is 2, we append 3 additional
# padding batches: b1, b2, b3.
# If user_provided_dataset contains two batches: a1, a2
# Step 1: [a1, a2]
# Step 2: [b1, b2] -> STOP
# If user_provided_dataset contains three batches: a1, a2, a3.
# The training loops:
# Step 1: [a1, a2]
# Step 2: [a3, b1]
# Step 3: [b2, b3] -> STOP.
final_batch_dataset = dataset.take(1).map(
_InputsWithStoppingSignals.insert_stopping_signal(
stop=True, batch_size=batch_size, add_padding=add_padding))
final_batch_dataset = final_batch_dataset.repeat(
2 * num_invocations_per_step - 1)
def _set_mask(data_dict):
signals = data_dict['signals']
signals['padding_mask'] = array_ops.ones_like(signals['padding_mask'])
data_dict['signals'] = signals
return data_dict
# Mask out the extra batch.
final_batch_dataset = final_batch_dataset.map(_set_mask)
dataset = user_provided_dataset.concatenate(final_batch_dataset).prefetch(2)
super(_InputsWithStoppingSignals, self).__init__(dataset=dataset)
self._current_inputs = None
def features_and_labels(self):
if self._current_inputs is not None:
raise RuntimeError(
'Internal Error: The previous inputs have not been properly '
'consumed. First call features_and_labels, then call signals.')
inputs_with_signals = self._iterator.get_next()
features = inputs_with_signals['features']
labels = inputs_with_signals.get('labels')
self._current_inputs = inputs_with_signals
return features, labels
def signals(self):
"""Returns the `Signals` from `_Inputs`."""
if self._current_inputs is None:
raise RuntimeError(
'Internal Error: The current inputs have not been properly '
'generated. First call features_and_labels, then call signals.')
signals = self._current_inputs['signals']
self._current_inputs = None
return signals
@staticmethod
def insert_stopping_signal(stop, batch_size, add_padding=False):
"""Inserts stopping_signal into dataset via _map_fn.
Here we change the data structure in the dataset, such that the return value
is a dictionary now and `features`, `labels`, and `signals` are three
distinguished keys in that dict. This provides a better structure, which
eases the process to decompose the inputs (see `features_and_labels`).
Args:
stop: bool, state of current stopping signals.
batch_size: int, batch size.
add_padding: bool, whether to pad the tensor to full batch size.
Returns:
A map_fn passed to dataset.map API.
"""
def _map_fn(*args):
"""The map fn to insert signals."""
if len(args) == 1:
# Unpack the single Tensor/dict argument as features. This is required
# for the input_fn returns no labels.
args = args[0]
features, labels = _Inputs._parse_inputs(args)
new_input_dict = {}
if add_padding:
padding_mask, features, labels = (
_PaddingSignals.pad_features_and_labels(features, labels,
batch_size))
new_input_dict['features'] = features
if labels is not None:
new_input_dict['labels'] = labels
else:
new_input_dict['features'] = features
if labels is not None:
new_input_dict['labels'] = labels
padding_mask = None
new_input_dict['signals'] = _StopSignals(
stop=stop, batch_size=batch_size,
padding_mask=padding_mask).as_dict()
return new_input_dict
return _map_fn
class _StopSignals(object):
"""Signals class holding all logic to handle TPU stopping condition."""
NON_STOPPING_SIGNAL = False
STOPPING_SIGNAL = True
def __init__(self, stop, batch_size, padding_mask=None):
self._stop = stop
self._batch_size = batch_size
self._padding_mask = padding_mask
def as_dict(self):
"""Returns the signals as Python dict."""
shape = [self._batch_size, 1]
dtype = dtypes.bool
if self._stop:
stopping = array_ops.ones(shape=shape, dtype=dtype)
else:
stopping = array_ops.zeros(shape=shape, dtype=dtype)
signals = {'stopping': stopping}
if self._padding_mask is not None:
signals['padding_mask'] = self._padding_mask
return signals
@staticmethod
def as_scalar_stopping_signal(signals):
return array_ops.identity(signals['stopping'][0][0])
@staticmethod
def should_stop(scalar_stopping_signal):
"""Detects whether scalar_stopping_signal indicates stopping."""
if isinstance(scalar_stopping_signal, ops.Tensor):
# STOPPING_SIGNAL is a constant True. Here, the logical_and is just the TF
# way to express the bool check whether scalar_stopping_signal is True.
return math_ops.logical_and(scalar_stopping_signal,
_StopSignals.STOPPING_SIGNAL)
else:
# For non Tensor case, it is used in SessionRunHook. So, we cannot modify
# the graph anymore. Here, we use pure Python.
return bool(scalar_stopping_signal)
class _PaddingSignals(object):
"""Signals class holding all logic to handle padding."""
@staticmethod
def pad_features_and_labels(features, labels, batch_size):
"""Pads out the batch dimension of features and labels."""
real_batch_size = array_ops.shape(
_PaddingSignals._find_any_tensor(features))[0]
batch_size_tensor = constant_op.constant(batch_size, dtypes.int32)
check_greater = check_ops.assert_greater_equal(
batch_size_tensor,
real_batch_size,
data=(batch_size_tensor, real_batch_size),
message='The real batch size should not be greater than batch_size.')
with ops.control_dependencies([check_greater]):
missing_count = batch_size_tensor - real_batch_size
def pad_single_tensor(tensor):
"""Pads out the batch dimension of a tensor to the complete batch_size."""
rank = len(tensor.shape)
assert rank > 0
padding = array_ops.stack([[0, missing_count]] + [[0, 0]] * (rank - 1))
padded_shape = (batch_size,) + tuple(tensor.shape[1:])
padded_tensor = array_ops.pad(tensor, padding)
padded_tensor.set_shape(padded_shape)
return padded_tensor
def nest_pad(tensor_or_dict):
return nest.map_structure(pad_single_tensor, tensor_or_dict)
features = nest_pad(features)
if labels is not None:
labels = nest_pad(labels)
padding_mask = _PaddingSignals._padding_mask(real_batch_size, missing_count,
batch_size)
return padding_mask, features, labels
@staticmethod
def slice_tensor_or_dict(tensor_or_dict, signals):
"""Slice the real Tensors according to padding mask in signals."""
padding_mask = signals['padding_mask']
batch_size = array_ops.shape(padding_mask)[0]
def verify_batch_size(tensor):
check_batch_size = math_ops.equal(batch_size, tensor.shape[0])
with ops.control_dependencies([check_batch_size]):
return array_ops.identity(tensor)
def slice_single_tensor(tensor):
rank = len(tensor.shape)
assert rank > 0
real_batch_size = batch_size - math_ops.reduce_sum(padding_mask)
return verify_batch_size(tensor)[0:real_batch_size]
# As we split the Tensors to all TPU cores and concat them back, it is
# important to ensure the real data is placed before padded ones, i.e.,
# order is preserved. By that, the sliced padding mask should have all 0's.
# If this assertion failed, # the slice logic here would not hold.
sliced_padding_mask = slice_single_tensor(padding_mask)
assert_padding_mask = math_ops.equal(
math_ops.reduce_sum(sliced_padding_mask), 0)
with ops.control_dependencies([assert_padding_mask]):
should_stop = _StopSignals.should_stop(
_StopSignals.as_scalar_stopping_signal(signals))
is_full_batch = math_ops.equal(math_ops.reduce_sum(padding_mask), 0)
def slice_fn(tensor):
# If the current batch is full batch or part of stopping signals, we do
# not need to slice to save performance.
return control_flow_ops.cond(
math_ops.logical_or(should_stop, is_full_batch),
(lambda: verify_batch_size(tensor)),
(lambda: slice_single_tensor(tensor)))
return nest.map_structure(slice_fn, tensor_or_dict)
@staticmethod
def _find_any_tensor(batch_features):
tensors = [
x for x in nest.flatten(batch_features) if isinstance(x, ops.Tensor)
]
if not tensors:
raise ValueError('Cannot find any Tensor in features dict.')
return tensors[0]
@staticmethod
def _padding_mask(real_batch_size, missing_count, batch_size):
padding_mask = array_ops.concat([
array_ops.zeros((real_batch_size,), dtype=dtypes.int32),
array_ops.ones((missing_count,), dtype=dtypes.int32)
],
axis=0)
padding_mask.set_shape((batch_size,))
return padding_mask
def _verify_cross_hosts_transfer_size(tensor_dict, message):
total_size = 0
tensor_structure = {}
for key, tensor in tensor_dict.items():
shape = tensor.shape
size = np.product(shape) * tensor.dtype.size
tensor_structure[key] = shape
total_size += size
if total_size >= _ONE_GIGABYTE:
raise ValueError(
'{} The transfer size is larger than the protobuf limit. Please '
'consider to use Tensors with smaller shapes or reduce batch '
'size. Given:\n'
'{}'.format(
message, '\n'.join([
' -- Key: {}, Shape: {}'.format(k, v)
for k, v in tensor_structure.items()
])))
def _add_item_to_params(params, key, value):
"""Adds a new item into `params`."""
if isinstance(params, hparam.HParams):
# For HParams, we need to use special API.
if key in params:
params.set_hparam(key, value)
else:
params.add_hparam(key, value)
else:
# Now params is Python dict.
params[key] = value
def export_estimator_savedmodel(estimator,
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False):
"""Export `Estimator` trained model for TPU inference.
Args:
estimator: `Estimator` with which model has been trained.
export_dir_base: A string containing a directory in which to create
timestamped subdirectories containing exported SavedModels.
serving_input_receiver_fn: A function that takes no argument and returns a
`ServingInputReceiver` or `TensorServingInputReceiver`.
assets_extra: A dict specifying how to populate the assets.extra directory
within the exported SavedModel, or `None` if no extra assets are needed.
as_text: whether to write the SavedModel proto in text format.
checkpoint_path: The checkpoint path to export. If `None` (the default),
the most recent checkpoint found within the model directory is chosen.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
removed from the NodeDefs.
Returns:
The string path to the exported directory.
"""
# `TPUEstimator` requires `tpu_config.RunConfig`, so we cannot use
# `estimator.config`.
config = tpu_config.RunConfig(model_dir=estimator.model_dir)
est = TPUEstimator(
estimator._model_fn, # pylint: disable=protected-access
config=config,
params=estimator.params,
use_tpu=True,
train_batch_size=2048, # Does not matter.
eval_batch_size=2048, # Does not matter.
)
return est.export_savedmodel(export_dir_base, serving_input_receiver_fn,
assets_extra, as_text, checkpoint_path,
strip_default_attrs)
| 138,978 | 38.449049 | 112 | py |
CLUE | CLUE-master/baselines/models/xlnet/__init__.py | 0 | 0 | 0 | py | |
CLUE | CLUE-master/baselines/models/xlnet/summary.py | # -*- coding: utf-8 -*-
'''
print summary
'''
from __future__ import print_function
from collections import Counter, OrderedDict
import string
import re
import argparse
import json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import pdb
import os
import math
import numpy as np
import collections
from prettytable import PrettyTable
def print_summary():
lscmd = os.popen('ls '+sys.argv[1]+'/result.*').read()
result_list = lscmd.split()
num_args = len(result_list)
assert num_args==2 or num_args==3
dev_input_file = open(sys.argv[1]+'/result.dev', 'rb')
test_input_file = open(sys.argv[1]+'/result.test', 'rb')
if num_args==2:
print_table = PrettyTable(['#','DEV-AVG','DEV-EM','DEV-F1','TEST-AVG','TEST-EM','TEST-F1','FILE'])
elif num_args==3:
chl_input_file = open(sys.argv[1]+'/result.challenge', 'rb')
print_table = PrettyTable(['#','DEV-AVG','DEV-EM','DEV-F1','TEST-AVG','TEST-EM','TEST-F1','CHL-AVG','CHL-EM','CHL-F1','FILE'])
# style set
print_table.align['FILE'] = 'l'
print_table.float_format = '2.3'
# data fill
dev_avg = []
dev_em = []
dev_f1 = []
dev_file = []
for dline in dev_input_file.readlines():
dline = dline.strip()
if re.search('^{', dline):
ddict = json.loads(dline)
dev_avg.append(float(ddict['AVERAGE']))
dev_em.append(float(ddict['EM']))
dev_f1.append(float(ddict['F1']))
dev_file.append(ddict['FILE'])
test_avg = []
test_em = []
test_f1 = []
test_file = []
for dline in test_input_file.readlines():
dline = dline.strip()
if re.search('^{', dline):
ddict = json.loads(dline)
test_avg.append(float(ddict['AVERAGE']))
test_em.append(float(ddict['EM']))
test_f1.append(float(ddict['F1']))
test_file.append(ddict['FILE'])
if num_args==3:
chl_avg = []
chl_em = []
chl_f1 = []
chl_file = []
for dline in chl_input_file.readlines():
dline = dline.strip()
if re.search('^{', dline):
ddict = json.loads(dline)
chl_avg.append(float(ddict['AVERAGE']))
chl_em.append(float(ddict['EM']))
chl_f1.append(float(ddict['F1']))
chl_file.append(ddict['FILE'])
# print
if num_args == 2:
min_len = min(len(dev_avg),len(test_avg))
for k in range(min_len):
print_table.add_row([k+1, dev_avg[k], dev_em[k], dev_f1[k], test_avg[k], test_em[k], test_f1[k], dev_file[k]])
elif num_args == 3:
min_len = min(len(dev_avg),len(test_avg),len(chl_avg))
for k in range(min_len):
print_table.add_row([k+1, dev_avg[k], dev_em[k], dev_f1[k], test_avg[k], test_em[k], test_f1[k], chl_avg[k], chl_em[k], chl_f1[k], dev_file[k]])
if len(sys.argv)==3:
sk = sys.argv[2].upper()
print('sort key detected: {}'.format(sk))
print(print_table.get_string(sortby=sk, reversesort=True))
else:
print(print_table)
if num_args == 2:
summary_table = PrettyTable(['#','DEV-AVG','DEV-EM','DEV-F1','TEST-AVG','TEST-EM','TEST-F1','FILE'])
summary_table.add_row(["M", np.max(dev_avg), np.max(dev_em), np.max(dev_f1),
np.max(test_avg), np.max(test_em), np.max(test_f1),"-"])
summary_table.add_row(["A", np.mean(dev_avg), np.mean(dev_em), np.mean(dev_f1),
np.mean(test_avg), np.mean(test_em), np.mean(test_f1),"-"])
summary_table.add_row(["D", np.std(dev_avg), np.std(dev_em), np.std(dev_f1),
np.std(test_avg), np.std(test_em), np.std(test_f1),"-"])
elif num_args == 3:
summary_table = PrettyTable(['#','DEV-AVG','DEV-EM','DEV-F1','TEST-AVG','TEST-EM','TEST-F1','CHL-AVG','CHL-EM','CHL-F1','FILE'])
summary_table.add_row(["M", np.max(dev_avg), np.max(dev_em), np.max(dev_f1),
np.max(test_avg), np.max(test_em), np.max(test_f1),
np.max(chl_avg), np.max(chl_em), np.max(chl_f1), "-"])
summary_table.add_row(["A", np.mean(dev_avg), np.mean(dev_em), np.mean(dev_f1),
np.mean(test_avg), np.mean(test_em), np.mean(test_f1),
np.mean(chl_avg), np.mean(chl_em), np.mean(chl_f1), "-"])
summary_table.add_row(["D", np.std(dev_avg), np.std(dev_em), np.std(dev_f1),
np.std(test_avg), np.std(test_em), np.std(test_f1),
np.std(chl_avg), np.std(chl_em), np.std(chl_f1), "-"])
# style set
summary_table.align['FILE'] = 'l'
summary_table.float_format = '2.3'
print(summary_table)
return 0
if __name__ == '__main__':
print_summary()
| 4,252 | 31.968992 | 147 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/run_classifier_with_tfhub.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BERT finetuning runner with TF-Hub."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import optimization
import run_classifier
import tokenization
import tensorflow as tf
import tensorflow_hub as hub
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_string(
"bert_hub_module_handle", None,
"Handle for the BERT TF-Hub module.")
def create_model(is_training, input_ids, input_mask, segment_ids, labels,
num_labels, bert_hub_module_handle):
"""Creates a classification model."""
tags = set()
if is_training:
tags.add("train")
bert_module = hub.Module(bert_hub_module_handle, tags=tags, trainable=True)
bert_inputs = dict(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids)
bert_outputs = bert_module(
inputs=bert_inputs,
signature="tokens",
as_dict=True)
# In the demo, we are doing a simple classification task on the entire
# segment.
#
# If you want to use the token-level output, use
# bert_outputs["sequence_output"] instead.
output_layer = bert_outputs["pooled_output"]
hidden_size = output_layer.shape[-1].value
output_weights = tf.get_variable(
"output_weights", [num_labels, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer())
with tf.variable_scope("loss"):
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax(logits, axis=-1)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, logits, probabilities)
def model_fn_builder(num_labels, learning_rate, num_train_steps,
num_warmup_steps, use_tpu, bert_hub_module_handle):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(total_loss, per_example_loss, logits, probabilities) = create_model(
is_training, input_ids, input_mask, segment_ids, label_ids, num_labels,
bert_hub_module_handle)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
accuracy = tf.metrics.accuracy(label_ids, predictions)
loss = tf.metrics.mean(per_example_loss)
return {
"eval_accuracy": accuracy,
"eval_loss": loss,
}
eval_metrics = (metric_fn, [per_example_loss, label_ids, logits])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics)
elif mode == tf.estimator.ModeKeys.PREDICT:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions={"probabilities": probabilities})
else:
raise ValueError(
"Only TRAIN, EVAL and PREDICT modes are supported: %s" % (mode))
return output_spec
return model_fn
def create_tokenizer_from_hub_module(bert_hub_module_handle):
"""Get the vocab file and casing info from the Hub module."""
with tf.Graph().as_default():
bert_module = hub.Module(bert_hub_module_handle)
tokenization_info = bert_module(signature="tokenization_info", as_dict=True)
with tf.Session() as sess:
vocab_file, do_lower_case = sess.run([tokenization_info["vocab_file"],
tokenization_info["do_lower_case"]])
return tokenization.FullTokenizer(
vocab_file=vocab_file, do_lower_case=do_lower_case)
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"cola": run_classifier.ColaProcessor,
"mnli": run_classifier.MnliProcessor,
"mrpc": run_classifier.MrpcProcessor,
}
if not FLAGS.do_train and not FLAGS.do_eval:
raise ValueError("At least one of `do_train` or `do_eval` must be True.")
tf.gfile.MakeDirs(FLAGS.output_dir)
task_name = FLAGS.task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
label_list = processor.get_labels()
tokenizer = create_tokenizer_from_hub_module(FLAGS.bert_hub_module_handle)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = processor.get_train_examples(FLAGS.data_dir)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
model_fn = model_fn_builder(
num_labels=len(label_list),
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
bert_hub_module_handle=FLAGS.bert_hub_module_handle)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
train_features = run_classifier.convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = run_classifier.input_fn_builder(
features=train_features,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_eval:
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
eval_features = run_classifier.convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d", len(eval_examples))
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
# This tells the estimator to run through the entire set.
eval_steps = None
# However, if running eval on the TPU, you will need to specify the
# number of steps.
if FLAGS.use_tpu:
# Eval will be slightly WRONG on the TPU because it will truncate
# the last batch.
eval_steps = int(len(eval_examples) / FLAGS.eval_batch_size)
eval_drop_remainder = True if FLAGS.use_tpu else False
eval_input_fn = run_classifier.input_fn_builder(
features=eval_features,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=eval_drop_remainder)
result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_predict:
predict_examples = processor.get_test_examples(FLAGS.data_dir)
if FLAGS.use_tpu:
# Discard batch remainder if running on TPU
n = len(predict_examples)
predict_examples = predict_examples[:(n - n % FLAGS.predict_batch_size)]
predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
run_classifier.file_based_convert_examples_to_features(
predict_examples, label_list, FLAGS.max_seq_length, tokenizer,
predict_file)
tf.logging.info("***** Running prediction*****")
tf.logging.info(" Num examples = %d", len(predict_examples))
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
predict_input_fn = run_classifier.file_based_input_fn_builder(
input_file=predict_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=FLAGS.use_tpu)
result = estimator.predict(input_fn=predict_input_fn)
output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
with tf.gfile.GFile(output_predict_file, "w") as writer:
tf.logging.info("***** Predict results *****")
for prediction in result:
probabilities = prediction["probabilities"]
output_line = "\t".join(
str(class_probability)
for class_probability in probabilities) + "\n"
writer.write(output_line)
if __name__ == "__main__":
flags.mark_flag_as_required("data_dir")
flags.mark_flag_as_required("task_name")
flags.mark_flag_as_required("bert_hub_module_handle")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| 11,426 | 35.27619 | 82 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Functions and classes related to optimization (weight updates)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import tensorflow as tf
def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu):
"""Creates an optimizer training op."""
global_step = tf.train.get_or_create_global_step()
learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32)
# Implements linear decay of the learning rate.
learning_rate = tf.train.polynomial_decay(
learning_rate,
global_step,
num_train_steps,
end_learning_rate=0.0,
power=1.0,
cycle=False)
# Implements linear warmup. I.e., if global_step < num_warmup_steps, the
# learning rate will be `global_step/num_warmup_steps * init_lr`.
if num_warmup_steps:
global_steps_int = tf.cast(global_step, tf.int32)
warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32)
global_steps_float = tf.cast(global_steps_int, tf.float32)
warmup_steps_float = tf.cast(warmup_steps_int, tf.float32)
warmup_percent_done = global_steps_float / warmup_steps_float
warmup_learning_rate = init_lr * warmup_percent_done
is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32)
learning_rate = (
(1.0 - is_warmup) * learning_rate + is_warmup * warmup_learning_rate)
# It is recommended that you use this optimizer for fine tuning, since this
# is how the model was trained (note that the Adam m/v variables are NOT
# loaded from init_checkpoint.)
optimizer = AdamWeightDecayOptimizer(
learning_rate=learning_rate,
weight_decay_rate=0.01,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-6,
exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"])
if use_tpu:
optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
tvars = tf.trainable_variables()
grads = tf.gradients(loss, tvars)
# This is how the model was pre-trained.
(grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0)
train_op = optimizer.apply_gradients(
zip(grads, tvars), global_step=global_step)
# Normally the global step update is done inside of `apply_gradients`.
# However, `AdamWeightDecayOptimizer` doesn't do this. But if you use
# a different optimizer, you should probably take this line out.
new_global_step = global_step + 1
train_op = tf.group(train_op, [global_step.assign(new_global_step)])
return train_op
class AdamWeightDecayOptimizer(tf.train.Optimizer):
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self,
learning_rate,
weight_decay_rate=0.0,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-6,
exclude_from_weight_decay=None,
name="AdamWeightDecayOptimizer"):
"""Constructs a AdamWeightDecayOptimizer."""
super(AdamWeightDecayOptimizer, self).__init__(False, name)
self.learning_rate = learning_rate
self.weight_decay_rate = weight_decay_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
self.exclude_from_weight_decay = exclude_from_weight_decay
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""See base class."""
assignments = []
for (grad, param) in grads_and_vars:
if grad is None or param is None:
continue
param_name = self._get_variable_name(param.name)
m = tf.get_variable(
name=param_name + "/adam_m",
shape=param.shape.as_list(),
dtype=tf.float32,
trainable=False,
initializer=tf.zeros_initializer())
v = tf.get_variable(
name=param_name + "/adam_v",
shape=param.shape.as_list(),
dtype=tf.float32,
trainable=False,
initializer=tf.zeros_initializer())
# Standard Adam update.
next_m = (
tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad))
next_v = (
tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2,
tf.square(grad)))
update = next_m / (tf.sqrt(next_v) + self.epsilon)
# Just adding the square of the weights to the loss function is *not*
# the correct way of using L2 regularization/weight decay with Adam,
# since that will interact with the m and v parameters in strange ways.
#
# Instead we want ot decay the weights in a manner that doesn't interact
# with the m/v parameters. This is equivalent to adding the square
# of the weights to the loss with plain (non-momentum) SGD.
if self._do_use_weight_decay(param_name):
update += self.weight_decay_rate * param
update_with_lr = self.learning_rate * update
next_param = param - update_with_lr
assignments.extend(
[param.assign(next_param),
m.assign(next_m),
v.assign(next_v)])
return tf.group(*assignments, name=name)
def _do_use_weight_decay(self, param_name):
"""Whether to use L2 weight decay for `param_name`."""
if not self.weight_decay_rate:
return False
if self.exclude_from_weight_decay:
for r in self.exclude_from_weight_decay:
if re.search(r, param_name) is not None:
return False
return True
def _get_variable_name(self, param_name):
"""Get the variable name from the tensor name."""
m = re.match("^(.*):\\d+$", param_name)
if m is not None:
param_name = m.group(1)
return param_name
| 6,258 | 34.765714 | 80 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/run_squad.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run BERT on SQuAD 1.1 and SQuAD 2.0."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import json
import math
import os
import random
import modeling
import optimization
import tokenization
import six
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written.")
## Other parameters
flags.DEFINE_string("train_file", None,
"SQuAD json for training. E.g., train-v1.1.json")
flags.DEFINE_string(
"predict_file", None,
"SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json")
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_integer(
"max_seq_length", 384,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded.")
flags.DEFINE_integer(
"doc_stride", 128,
"When splitting up a long document into chunks, how much stride to "
"take between chunks.")
flags.DEFINE_integer(
"max_query_length", 64,
"The maximum number of tokens for the question. Questions longer than "
"this will be truncated to this length.")
flags.DEFINE_bool("do_train", False, "Whether to run training.")
flags.DEFINE_bool("do_predict", False, "Whether to run eval on the dev set.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("predict_batch_size", 8,
"Total batch size for predictions.")
flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
flags.DEFINE_float("num_train_epochs", 3.0,
"Total number of training epochs to perform.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_integer(
"n_best_size", 20,
"The total number of n-best predictions to generate in the "
"nbest_predictions.json output file.")
flags.DEFINE_integer(
"max_answer_length", 30,
"The maximum length of an answer that can be generated. This is needed "
"because the start and end predictions are not conditioned on one another.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
tf.flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
tf.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
flags.DEFINE_bool(
"verbose_logging", False,
"If true, all of the warnings related to data processing will be printed. "
"A number of warnings are expected for a normal SQuAD evaluation.")
flags.DEFINE_bool(
"version_2_with_negative", False,
"If true, the SQuAD examples contain some that do not have an answer.")
flags.DEFINE_float(
"null_score_diff_threshold", 0.0,
"If null_score - best_non_null is greater than the threshold predict null.")
class SquadExample(object):
"""A single training/test example for simple sequence classification.
For examples without an answer, the start and end position are -1.
"""
def __init__(self,
qas_id,
question_text,
doc_tokens,
orig_answer_text=None,
start_position=None,
end_position=None,
is_impossible=False):
self.qas_id = qas_id
self.question_text = question_text
self.doc_tokens = doc_tokens
self.orig_answer_text = orig_answer_text
self.start_position = start_position
self.end_position = end_position
self.is_impossible = is_impossible
def __str__(self):
return self.__repr__()
def __repr__(self):
s = ""
s += "qas_id: %s" % (tokenization.printable_text(self.qas_id))
s += ", question_text: %s" % (
tokenization.printable_text(self.question_text))
s += ", doc_tokens: [%s]" % (" ".join(self.doc_tokens))
if self.start_position:
s += ", start_position: %d" % (self.start_position)
if self.start_position:
s += ", end_position: %d" % (self.end_position)
if self.start_position:
s += ", is_impossible: %r" % (self.is_impossible)
return s
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
unique_id,
example_index,
doc_span_index,
tokens,
token_to_orig_map,
token_is_max_context,
input_ids,
input_mask,
segment_ids,
start_position=None,
end_position=None,
is_impossible=None):
self.unique_id = unique_id
self.example_index = example_index
self.doc_span_index = doc_span_index
self.tokens = tokens
self.token_to_orig_map = token_to_orig_map
self.token_is_max_context = token_is_max_context
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.start_position = start_position
self.end_position = end_position
self.is_impossible = is_impossible
def read_squad_examples(input_file, is_training):
"""Read a SQuAD json file into a list of SquadExample."""
with tf.gfile.Open(input_file, "r") as reader:
input_data = json.load(reader)["data"]
def is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
examples = []
for entry in input_data:
for paragraph in entry["paragraphs"]:
paragraph_text = paragraph["context"]
doc_tokens = []
char_to_word_offset = []
prev_is_whitespace = True
for c in paragraph_text:
if is_whitespace(c):
prev_is_whitespace = True
else:
if prev_is_whitespace:
doc_tokens.append(c)
else:
doc_tokens[-1] += c
prev_is_whitespace = False
char_to_word_offset.append(len(doc_tokens) - 1)
for qa in paragraph["qas"]:
qas_id = qa["id"]
question_text = qa["question"]
start_position = None
end_position = None
orig_answer_text = None
is_impossible = False
if is_training:
if FLAGS.version_2_with_negative:
is_impossible = qa["is_impossible"]
if (len(qa["answers"]) != 1) and (not is_impossible):
raise ValueError(
"For training, each question should have exactly 1 answer.")
if not is_impossible:
answer = qa["answers"][0]
orig_answer_text = answer["text"]
answer_offset = answer["answer_start"]
answer_length = len(orig_answer_text)
start_position = char_to_word_offset[answer_offset]
end_position = char_to_word_offset[answer_offset + answer_length -
1]
# Only add answers where the text can be exactly recovered from the
# document. If this CAN'T happen it's likely due to weird Unicode
# stuff so we will just skip the example.
#
# Note that this means for training mode, every example is NOT
# guaranteed to be preserved.
actual_text = " ".join(
doc_tokens[start_position:(end_position + 1)])
cleaned_answer_text = " ".join(
tokenization.whitespace_tokenize(orig_answer_text))
if actual_text.find(cleaned_answer_text) == -1:
tf.logging.warning("Could not find answer: '%s' vs. '%s'",
actual_text, cleaned_answer_text)
continue
else:
start_position = -1
end_position = -1
orig_answer_text = ""
example = SquadExample(
qas_id=qas_id,
question_text=question_text,
doc_tokens=doc_tokens,
orig_answer_text=orig_answer_text,
start_position=start_position,
end_position=end_position,
is_impossible=is_impossible)
examples.append(example)
return examples
def convert_examples_to_features(examples, tokenizer, max_seq_length,
doc_stride, max_query_length, is_training,
output_fn):
"""Loads a data file into a list of `InputBatch`s."""
unique_id = 1000000000
for (example_index, example) in enumerate(examples):
query_tokens = tokenizer.tokenize(example.question_text)
if len(query_tokens) > max_query_length:
query_tokens = query_tokens[0:max_query_length]
tok_to_orig_index = []
orig_to_tok_index = []
all_doc_tokens = []
for (i, token) in enumerate(example.doc_tokens):
orig_to_tok_index.append(len(all_doc_tokens))
sub_tokens = tokenizer.tokenize(token)
for sub_token in sub_tokens:
tok_to_orig_index.append(i)
all_doc_tokens.append(sub_token)
tok_start_position = None
tok_end_position = None
if is_training and example.is_impossible:
tok_start_position = -1
tok_end_position = -1
if is_training and not example.is_impossible:
tok_start_position = orig_to_tok_index[example.start_position]
if example.end_position < len(example.doc_tokens) - 1:
tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
else:
tok_end_position = len(all_doc_tokens) - 1
(tok_start_position, tok_end_position) = _improve_answer_span(
all_doc_tokens, tok_start_position, tok_end_position, tokenizer,
example.orig_answer_text)
# The -3 accounts for [CLS], [SEP] and [SEP]
max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
# We can have documents that are longer than the maximum sequence length.
# To deal with this we do a sliding window approach, where we take chunks
# of the up to our max length with a stride of `doc_stride`.
_DocSpan = collections.namedtuple( # pylint: disable=invalid-name
"DocSpan", ["start", "length"])
doc_spans = []
start_offset = 0
while start_offset < len(all_doc_tokens):
length = len(all_doc_tokens) - start_offset
if length > max_tokens_for_doc:
length = max_tokens_for_doc
doc_spans.append(_DocSpan(start=start_offset, length=length))
if start_offset + length == len(all_doc_tokens):
break
start_offset += min(length, doc_stride)
for (doc_span_index, doc_span) in enumerate(doc_spans):
tokens = []
token_to_orig_map = {}
token_is_max_context = {}
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
for i in range(doc_span.length):
split_token_index = doc_span.start + i
token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
is_max_context = _check_is_max_context(doc_spans, doc_span_index,
split_token_index)
token_is_max_context[len(tokens)] = is_max_context
tokens.append(all_doc_tokens[split_token_index])
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
start_position = None
end_position = None
if is_training and not example.is_impossible:
# For training, if our document chunk does not contain an annotation
# we throw it out, since there is nothing to predict.
doc_start = doc_span.start
doc_end = doc_span.start + doc_span.length - 1
out_of_span = False
if not (tok_start_position >= doc_start and
tok_end_position <= doc_end):
out_of_span = True
if out_of_span:
start_position = 0
end_position = 0
else:
doc_offset = len(query_tokens) + 2
start_position = tok_start_position - doc_start + doc_offset
end_position = tok_end_position - doc_start + doc_offset
if is_training and example.is_impossible:
start_position = 0
end_position = 0
if example_index < 20:
tf.logging.info("*** Example ***")
tf.logging.info("unique_id: %s" % (unique_id))
tf.logging.info("example_index: %s" % (example_index))
tf.logging.info("doc_span_index: %s" % (doc_span_index))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("token_to_orig_map: %s" % " ".join(
["%d:%d" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))
tf.logging.info("token_is_max_context: %s" % " ".join([
"%d:%s" % (x, y) for (x, y) in six.iteritems(token_is_max_context)
]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info(
"input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info(
"segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
if is_training and example.is_impossible:
tf.logging.info("impossible example")
if is_training and not example.is_impossible:
answer_text = " ".join(tokens[start_position:(end_position + 1)])
tf.logging.info("start_position: %d" % (start_position))
tf.logging.info("end_position: %d" % (end_position))
tf.logging.info(
"answer: %s" % (tokenization.printable_text(answer_text)))
feature = InputFeatures(
unique_id=unique_id,
example_index=example_index,
doc_span_index=doc_span_index,
tokens=tokens,
token_to_orig_map=token_to_orig_map,
token_is_max_context=token_is_max_context,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
start_position=start_position,
end_position=end_position,
is_impossible=example.is_impossible)
# Run callback
output_fn(feature)
unique_id += 1
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
orig_answer_text):
"""Returns tokenized answer spans that better match the annotated answer."""
# The SQuAD annotations are character based. We first project them to
# whitespace-tokenized words. But then after WordPiece tokenization, we can
# often find a "better match". For example:
#
# Question: What year was John Smith born?
# Context: The leader was John Smith (1895-1943).
# Answer: 1895
#
# The original whitespace-tokenized answer will be "(1895-1943).". However
# after tokenization, our tokens will be "( 1895 - 1943 ) .". So we can match
# the exact answer, 1895.
#
# However, this is not always possible. Consider the following:
#
# Question: What country is the top exporter of electornics?
# Context: The Japanese electronics industry is the lagest in the world.
# Answer: Japan
#
# In this case, the annotator chose "Japan" as a character sub-span of
# the word "Japanese". Since our WordPiece tokenizer does not split
# "Japanese", we just use "Japanese" as the annotation. This is fairly rare
# in SQuAD, but does happen.
tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
for new_start in range(input_start, input_end + 1):
for new_end in range(input_end, new_start - 1, -1):
text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
if text_span == tok_answer_text:
return (new_start, new_end)
return (input_start, input_end)
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a single
# token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a gallon of milk
# Span A: the man went to the
# Span B: to the store and bought
# Span C: and bought a gallon of
# ...
#
# Now the word 'bought' will have two scores from spans B and C. We only
# want to consider the score with "maximum context", which we define as
# the *minimum* of its left and right context (the *sum* of left and
# right context will always be the same, of course).
#
# In the example the maximum context for 'bought' would be span C since
# it has 1 left context and 3 right context, while span B has 4 left context
# and 0 right context.
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
use_one_hot_embeddings):
"""Creates a classification model."""
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
final_hidden = model.get_sequence_output()
final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)
batch_size = final_hidden_shape[0]
seq_length = final_hidden_shape[1]
hidden_size = final_hidden_shape[2]
output_weights = tf.get_variable(
"cls/squad/output_weights", [2, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"cls/squad/output_bias", [2], initializer=tf.zeros_initializer())
final_hidden_matrix = tf.reshape(final_hidden,
[batch_size * seq_length, hidden_size])
logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
logits = tf.reshape(logits, [batch_size, seq_length, 2])
logits = tf.transpose(logits, [2, 0, 1])
unstacked_logits = tf.unstack(logits, axis=0)
(start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])
return (start_logits, end_logits)
def model_fn_builder(bert_config, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
unique_ids = features["unique_ids"]
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(start_logits, end_logits) = create_model(
bert_config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
seq_length = modeling.get_shape_list(input_ids)[1]
def compute_loss(logits, positions):
one_hot_positions = tf.one_hot(
positions, depth=seq_length, dtype=tf.float32)
log_probs = tf.nn.log_softmax(logits, axis=-1)
loss = -tf.reduce_mean(
tf.reduce_sum(one_hot_positions * log_probs, axis=-1))
return loss
start_positions = features["start_positions"]
end_positions = features["end_positions"]
start_loss = compute_loss(start_logits, start_positions)
end_loss = compute_loss(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2.0
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
"unique_ids": unique_ids,
"start_logits": start_logits,
"end_logits": end_logits,
}
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
else:
raise ValueError(
"Only TRAIN and PREDICT modes are supported: %s" % (mode))
return output_spec
return model_fn
def input_fn_builder(input_file, seq_length, is_training, drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"unique_ids": tf.FixedLenFeature([], tf.int64),
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
}
if is_training:
name_to_features["start_positions"] = tf.FixedLenFeature([], tf.int64)
name_to_features["end_positions"] = tf.FixedLenFeature([], tf.int64)
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder))
return d
return input_fn
RawResult = collections.namedtuple("RawResult",
["unique_id", "start_logits", "end_logits"])
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, do_lower_case, output_prediction_file,
output_nbest_file, output_null_log_odds_file):
"""Write final predictions to the json file and log-odds of null if needed."""
tf.logging.info("Writing predictions to: %s" % (output_prediction_file))
tf.logging.info("Writing nbest to: %s" % (output_nbest_file))
example_index_to_features = collections.defaultdict(list)
for feature in all_features:
example_index_to_features[feature.example_index].append(feature)
unique_id_to_result = {}
for result in all_results:
unique_id_to_result[result.unique_id] = result
_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
"PrelimPrediction",
["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
all_predictions = collections.OrderedDict()
all_nbest_json = collections.OrderedDict()
scores_diff_json = collections.OrderedDict()
for (example_index, example) in enumerate(all_examples):
features = example_index_to_features[example_index]
prelim_predictions = []
# keep track of the minimum score of null start+end of position 0
score_null = 1000000 # large and positive
min_null_feature_index = 0 # the paragraph slice with min mull score
null_start_logit = 0 # the start logit at the slice with min null score
null_end_logit = 0 # the end logit at the slice with min null score
for (feature_index, feature) in enumerate(features):
result = unique_id_to_result[feature.unique_id]
start_indexes = _get_best_indexes(result.start_logits, n_best_size)
end_indexes = _get_best_indexes(result.end_logits, n_best_size)
# if we could have irrelevant answers, get the min score of irrelevant
if FLAGS.version_2_with_negative:
feature_null_score = result.start_logits[0] + result.end_logits[0]
if feature_null_score < score_null:
score_null = feature_null_score
min_null_feature_index = feature_index
null_start_logit = result.start_logits[0]
null_end_logit = result.end_logits[0]
for start_index in start_indexes:
for end_index in end_indexes:
# We could hypothetically create invalid predictions, e.g., predict
# that the start of the span is in the question. We throw out all
# invalid predictions.
if start_index >= len(feature.tokens):
continue
if end_index >= len(feature.tokens):
continue
if start_index not in feature.token_to_orig_map:
continue
if end_index not in feature.token_to_orig_map:
continue
if not feature.token_is_max_context.get(start_index, False):
continue
if end_index < start_index:
continue
length = end_index - start_index + 1
if length > max_answer_length:
continue
prelim_predictions.append(
_PrelimPrediction(
feature_index=feature_index,
start_index=start_index,
end_index=end_index,
start_logit=result.start_logits[start_index],
end_logit=result.end_logits[end_index]))
if FLAGS.version_2_with_negative:
prelim_predictions.append(
_PrelimPrediction(
feature_index=min_null_feature_index,
start_index=0,
end_index=0,
start_logit=null_start_logit,
end_logit=null_end_logit))
prelim_predictions = sorted(
prelim_predictions,
key=lambda x: (x.start_logit + x.end_logit),
reverse=True)
_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
"NbestPrediction", ["text", "start_logit", "end_logit"])
seen_predictions = {}
nbest = []
for pred in prelim_predictions:
if len(nbest) >= n_best_size:
break
feature = features[pred.feature_index]
if pred.start_index > 0: # this is a non-null prediction
tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]
orig_doc_start = feature.token_to_orig_map[pred.start_index]
orig_doc_end = feature.token_to_orig_map[pred.end_index]
orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]
tok_text = " ".join(tok_tokens)
# De-tokenize WordPieces that have been split off.
tok_text = tok_text.replace(" ##", "")
tok_text = tok_text.replace("##", "")
# Clean whitespace
tok_text = tok_text.strip()
tok_text = " ".join(tok_text.split())
orig_text = " ".join(orig_tokens)
final_text = get_final_text(tok_text, orig_text, do_lower_case)
if final_text in seen_predictions:
continue
seen_predictions[final_text] = True
else:
final_text = ""
seen_predictions[final_text] = True
nbest.append(
_NbestPrediction(
text=final_text,
start_logit=pred.start_logit,
end_logit=pred.end_logit))
# if we didn't inlude the empty option in the n-best, inlcude it
if FLAGS.version_2_with_negative:
if "" not in seen_predictions:
nbest.append(
_NbestPrediction(
text="", start_logit=null_start_logit,
end_logit=null_end_logit))
# In very rare edge cases we could have no valid predictions. So we
# just create a nonce prediction in this case to avoid failure.
if not nbest:
nbest.append(
_NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
assert len(nbest) >= 1
total_scores = []
best_non_null_entry = None
for entry in nbest:
total_scores.append(entry.start_logit + entry.end_logit)
if not best_non_null_entry:
if entry.text:
best_non_null_entry = entry
probs = _compute_softmax(total_scores)
nbest_json = []
for (i, entry) in enumerate(nbest):
output = collections.OrderedDict()
output["text"] = entry.text
output["probability"] = probs[i]
output["start_logit"] = entry.start_logit
output["end_logit"] = entry.end_logit
nbest_json.append(output)
assert len(nbest_json) >= 1
if not FLAGS.version_2_with_negative:
all_predictions[example.qas_id] = nbest_json[0]["text"]
else:
# predict "" iff the null score - the score of best non-null > threshold
score_diff = score_null - best_non_null_entry.start_logit - (
best_non_null_entry.end_logit)
scores_diff_json[example.qas_id] = score_diff
if score_diff > FLAGS.null_score_diff_threshold:
all_predictions[example.qas_id] = ""
else:
all_predictions[example.qas_id] = best_non_null_entry.text
all_nbest_json[example.qas_id] = nbest_json
with tf.gfile.GFile(output_prediction_file, "w") as writer:
writer.write(json.dumps(all_predictions, indent=4) + "\n")
with tf.gfile.GFile(output_nbest_file, "w") as writer:
writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
if FLAGS.version_2_with_negative:
with tf.gfile.GFile(output_null_log_odds_file, "w") as writer:
writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
def get_final_text(pred_text, orig_text, do_lower_case):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `orig_text` contains the span of our original text corresponding to the
# span that we predicted.
#
# However, `orig_text` may contain extra characters that we don't want in
# our prediction.
#
# For example, let's say:
# pred_text = steve smith
# orig_text = Steve Smith's
#
# We don't want to return `orig_text` because it contains the extra "'s".
#
# We don't want to return `pred_text` because it's already been normalized
# (the SQuAD eval script also does punctuation stripping/lower casing but
# our tokenizer does additional normalization like stripping accent
# characters).
#
# What we really want to return is "Steve Smith".
#
# Therefore, we have to apply a semi-complicated alignment heruistic between
# `pred_text` and `orig_text` to get a character-to-charcter alignment. This
# can fail in certain cases in which case we just return `orig_text`.
def _strip_spaces(text):
ns_chars = []
ns_to_s_map = collections.OrderedDict()
for (i, c) in enumerate(text):
if c == " ":
continue
ns_to_s_map[len(ns_chars)] = i
ns_chars.append(c)
ns_text = "".join(ns_chars)
return (ns_text, ns_to_s_map)
# We first tokenize `orig_text`, strip whitespace from the result
# and `pred_text`, and check if they are the same length. If they are
# NOT the same length, the heuristic has failed. If they are the same
# length, we assume the characters are one-to-one aligned.
tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)
tok_text = " ".join(tokenizer.tokenize(orig_text))
start_position = tok_text.find(pred_text)
if start_position == -1:
if FLAGS.verbose_logging:
tf.logging.info(
"Unable to find text: '%s' in '%s'" % (pred_text, orig_text))
return orig_text
end_position = start_position + len(pred_text) - 1
(orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
(tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
if len(orig_ns_text) != len(tok_ns_text):
if FLAGS.verbose_logging:
tf.logging.info("Length not equal after stripping spaces: '%s' vs '%s'",
orig_ns_text, tok_ns_text)
return orig_text
# We then project the characters in `pred_text` back to `orig_text` using
# the character-to-character alignment.
tok_s_to_ns_map = {}
for (i, tok_index) in six.iteritems(tok_ns_to_s_map):
tok_s_to_ns_map[tok_index] = i
orig_start_position = None
if start_position in tok_s_to_ns_map:
ns_start_position = tok_s_to_ns_map[start_position]
if ns_start_position in orig_ns_to_s_map:
orig_start_position = orig_ns_to_s_map[ns_start_position]
if orig_start_position is None:
if FLAGS.verbose_logging:
tf.logging.info("Couldn't map start position")
return orig_text
orig_end_position = None
if end_position in tok_s_to_ns_map:
ns_end_position = tok_s_to_ns_map[end_position]
if ns_end_position in orig_ns_to_s_map:
orig_end_position = orig_ns_to_s_map[ns_end_position]
if orig_end_position is None:
if FLAGS.verbose_logging:
tf.logging.info("Couldn't map end position")
return orig_text
output_text = orig_text[orig_start_position:(orig_end_position + 1)]
return output_text
def _get_best_indexes(logits, n_best_size):
"""Get the n-best logits from a list."""
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if i >= n_best_size:
break
best_indexes.append(index_and_score[i][0])
return best_indexes
def _compute_softmax(scores):
"""Compute softmax probability over raw logits."""
if not scores:
return []
max_score = None
for score in scores:
if max_score is None or score > max_score:
max_score = score
exp_scores = []
total_sum = 0.0
for score in scores:
x = math.exp(score - max_score)
exp_scores.append(x)
total_sum += x
probs = []
for score in exp_scores:
probs.append(score / total_sum)
return probs
class FeatureWriter(object):
"""Writes InputFeature to TF example file."""
def __init__(self, filename, is_training):
self.filename = filename
self.is_training = is_training
self.num_features = 0
self._writer = tf.python_io.TFRecordWriter(filename)
def process_feature(self, feature):
"""Write a InputFeature to the TFRecordWriter as a tf.train.Example."""
self.num_features += 1
def create_int_feature(values):
feature = tf.train.Feature(
int64_list=tf.train.Int64List(value=list(values)))
return feature
features = collections.OrderedDict()
features["unique_ids"] = create_int_feature([feature.unique_id])
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
if self.is_training:
features["start_positions"] = create_int_feature([feature.start_position])
features["end_positions"] = create_int_feature([feature.end_position])
impossible = 0
if feature.is_impossible:
impossible = 1
features["is_impossible"] = create_int_feature([impossible])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
self._writer.write(tf_example.SerializeToString())
def close(self):
self._writer.close()
def validate_flags_or_throw(bert_config):
"""Validate the input FLAGS or throw an exception."""
tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,
FLAGS.init_checkpoint)
if not FLAGS.do_train and not FLAGS.do_predict:
raise ValueError("At least one of `do_train` or `do_predict` must be True.")
if FLAGS.do_train:
if not FLAGS.train_file:
raise ValueError(
"If `do_train` is True, then `train_file` must be specified.")
if FLAGS.do_predict:
if not FLAGS.predict_file:
raise ValueError(
"If `do_predict` is True, then `predict_file` must be specified.")
if FLAGS.max_seq_length > bert_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, bert_config.max_position_embeddings))
if FLAGS.max_seq_length <= FLAGS.max_query_length + 3:
raise ValueError(
"The max_seq_length (%d) must be greater than max_query_length "
"(%d) + 3" % (FLAGS.max_seq_length, FLAGS.max_query_length))
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
validate_flags_or_throw(bert_config)
tf.gfile.MakeDirs(FLAGS.output_dir)
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = read_squad_examples(
input_file=FLAGS.train_file, is_training=True)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
# Pre-shuffle the input to avoid having to make a very large shuffle
# buffer in in the `input_fn`.
rng = random.Random(12345)
rng.shuffle(train_examples)
model_fn = model_fn_builder(
bert_config=bert_config,
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
# We write to a temporary file to avoid storing very large constant tensors
# in memory.
train_writer = FeatureWriter(
filename=os.path.join(FLAGS.output_dir, "train.tf_record"),
is_training=True)
convert_examples_to_features(
examples=train_examples,
tokenizer=tokenizer,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=True,
output_fn=train_writer.process_feature)
train_writer.close()
tf.logging.info("***** Running training *****")
tf.logging.info(" Num orig examples = %d", len(train_examples))
tf.logging.info(" Num split examples = %d", train_writer.num_features)
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
del train_examples
train_input_fn = input_fn_builder(
input_file=train_writer.filename,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_predict:
eval_examples = read_squad_examples(
input_file=FLAGS.predict_file, is_training=False)
eval_writer = FeatureWriter(
filename=os.path.join(FLAGS.output_dir, "eval.tf_record"),
is_training=False)
eval_features = []
def append_feature(feature):
eval_features.append(feature)
eval_writer.process_feature(feature)
convert_examples_to_features(
examples=eval_examples,
tokenizer=tokenizer,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=False,
output_fn=append_feature)
eval_writer.close()
tf.logging.info("***** Running predictions *****")
tf.logging.info(" Num orig examples = %d", len(eval_examples))
tf.logging.info(" Num split examples = %d", len(eval_features))
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
all_results = []
predict_input_fn = input_fn_builder(
input_file=eval_writer.filename,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=False)
# If running eval on the TPU, you will need to specify the number of
# steps.
all_results = []
for result in estimator.predict(
predict_input_fn, yield_single_examples=True):
if len(all_results) % 1000 == 0:
tf.logging.info("Processing example: %d" % (len(all_results)))
unique_id = int(result["unique_ids"])
start_logits = [float(x) for x in result["start_logits"].flat]
end_logits = [float(x) for x in result["end_logits"].flat]
all_results.append(
RawResult(
unique_id=unique_id,
start_logits=start_logits,
end_logits=end_logits))
output_prediction_file = os.path.join(FLAGS.output_dir, "predictions.json")
output_nbest_file = os.path.join(FLAGS.output_dir, "nbest_predictions.json")
output_null_log_odds_file = os.path.join(FLAGS.output_dir, "null_odds.json")
write_predictions(eval_examples, eval_features, all_results,
FLAGS.n_best_size, FLAGS.max_answer_length,
FLAGS.do_lower_case, output_prediction_file,
output_nbest_file, output_null_log_odds_file)
if __name__ == "__main__":
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| 46,532 | 35.240654 | 82 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/run_classifier.py | # -*- coding: utf-8 -*-
# @Author: bo.shi
# @Date: 2019-11-04 09:56:36
# @Last Modified by: bo.shi
# @Last Modified time: 2019-12-04 14:30:38
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BERT finetuning runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import modeling
import optimization
import tokenization
import tensorflow as tf
import sys
sys.path.append('..')
from classifier_utils import *
flags = tf.flags
FLAGS = flags.FLAGS
# Required parameters
flags.DEFINE_string(
"data_dir", None,
"The input data dir. Should contain the .tsv files (or other data files) "
"for the task.")
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_string("task_name", None, "The name of the task to train.")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written.")
# Other parameters
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_integer(
"max_seq_length", 128,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded.")
flags.DEFINE_bool("do_train", False, "Whether to run training.")
flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
flags.DEFINE_bool(
"do_predict", False,
"Whether to run the model in inference mode on the test set.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predict.")
flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
flags.DEFINE_float("num_train_epochs", 3.0,
"Total number of training epochs to perform.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
tf.flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
tf.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
input_ids,
input_mask,
segment_ids,
label_id,
is_real_example=True):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
self.is_real_example = is_real_example
def convert_single_example_for_inews(ex_index, tokens_a, tokens_b, label_map, max_seq_length,
tokenizer, example):
if tokens_b:
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for [CLS], [SEP], [SEP] with "- 3"
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
else:
# Account for [CLS] and [SEP] with "- 2"
if len(tokens_a) > max_seq_length - 2:
tokens_a = tokens_a[0:(max_seq_length - 2)]
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens = []
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in tokens_a:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
if tokens_b:
for token in tokens_b:
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
label_id = label_map[example.label]
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id,
is_real_example=True)
return feature
def convert_example_list_for_inews(ex_index, example, label_list, max_seq_length,
tokenizer):
"""Converts a single `InputExample` into a single `InputFeatures`."""
if isinstance(example, PaddingInputExample):
return [InputFeatures(
input_ids=[0] * max_seq_length,
input_mask=[0] * max_seq_length,
segment_ids=[0] * max_seq_length,
label_id=0,
is_real_example=False)]
label_map = {}
for (i, label) in enumerate(label_list):
label_map[label] = i
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
must_len = len(tokens_a) + 3
extra_len = max_seq_length - must_len
feature_list = []
if example.text_b and extra_len > 0:
extra_num = int((len(tokens_b) - 1) / extra_len) + 1
for num in range(extra_num):
max_len = min((num + 1) * extra_len, len(tokens_b))
tokens_b_sub = tokens_b[num * extra_len: max_len]
feature = convert_single_example_for_inews(
ex_index, tokens_a, tokens_b_sub, label_map, max_seq_length, tokenizer, example)
feature_list.append(feature)
else:
feature = convert_single_example_for_inews(
ex_index, tokens_a, tokens_b, label_map, max_seq_length, tokenizer, example)
feature_list.append(feature)
return feature_list
def file_based_convert_examples_to_features_for_inews(
examples, label_list, max_seq_length, tokenizer, output_file):
"""Convert a set of `InputExample`s to a TFRecord file."""
writer = tf.python_io.TFRecordWriter(output_file)
num_example = 0
for (ex_index, example) in enumerate(examples):
if ex_index % 1000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature_list = convert_example_list_for_inews(ex_index, example, label_list,
max_seq_length, tokenizer)
num_example += len(feature_list)
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
features = collections.OrderedDict()
for feature in feature_list:
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["label_ids"] = create_int_feature([feature.label_id])
features["is_real_example"] = create_int_feature(
[int(feature.is_real_example)])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
tf.logging.info("feature num: %s", num_example)
writer.close()
def convert_single_example(ex_index, example, label_list, max_seq_length,
tokenizer):
"""Converts a single `InputExample` into a single `InputFeatures`."""
if isinstance(example, PaddingInputExample):
return InputFeatures(
input_ids=[0] * max_seq_length,
input_mask=[0] * max_seq_length,
segment_ids=[0] * max_seq_length,
label_id=0,
is_real_example=False)
label_map = {}
for (i, label) in enumerate(label_list):
label_map[label] = i
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
if tokens_b:
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for [CLS], [SEP], [SEP] with "- 3"
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
else:
# Account for [CLS] and [SEP] with "- 2"
if len(tokens_a) > max_seq_length - 2:
tokens_a = tokens_a[0:(max_seq_length - 2)]
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens = []
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in tokens_a:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
if tokens_b:
for token in tokens_b:
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
label_id = label_map[example.label]
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id,
is_real_example=True)
return feature
def file_based_convert_examples_to_features(
examples, label_list, max_seq_length, tokenizer, output_file):
"""Convert a set of `InputExample`s to a TFRecord file."""
writer = tf.python_io.TFRecordWriter(output_file)
for (ex_index, example) in enumerate(examples):
if ex_index % 10000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature = convert_single_example(ex_index, example, label_list,
max_seq_length, tokenizer)
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
features = collections.OrderedDict()
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["label_ids"] = create_int_feature([feature.label_id])
features["is_real_example"] = create_int_feature(
[int(feature.is_real_example)])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
writer.close()
def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([], tf.int64),
"is_real_example": tf.FixedLenFeature([], tf.int64),
}
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder))
return d
return input_fn
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
labels, num_labels, use_one_hot_embeddings):
"""Creates a classification model."""
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
# In the demo, we are doing a simple classification task on the entire
# segment.
#
# If you want to use the token-level output, use model.get_sequence_output()
# instead.
output_layer = model.get_pooled_output()
hidden_size = output_layer.shape[-1].value
output_weights = tf.get_variable(
"output_weights", [num_labels, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer())
with tf.variable_scope("loss"):
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax(logits, axis=-1)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, logits, probabilities)
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]
is_real_example = None
if "is_real_example" in features:
is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32)
else:
is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(total_loss, per_example_loss, logits, probabilities) = create_model(
bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,
num_labels, use_one_hot_embeddings)
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
accuracy = tf.metrics.accuracy(
labels=label_ids, predictions=predictions, weights=is_real_example)
loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
return {
"eval_accuracy": accuracy,
"eval_loss": loss,
}
eval_metrics = (metric_fn,
[per_example_loss, label_ids, logits, is_real_example])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
predictions={"probabilities": probabilities},
scaffold_fn=scaffold_fn)
return output_spec
return model_fn
# This function is not used by this file but is still used by the Colab and
# people who depend on it.
def input_fn_builder(features, seq_length, is_training, drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
all_input_ids = []
all_input_mask = []
all_segment_ids = []
all_label_ids = []
for feature in features:
all_input_ids.append(feature.input_ids)
all_input_mask.append(feature.input_mask)
all_segment_ids.append(feature.segment_ids)
all_label_ids.append(feature.label_id)
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
num_examples = len(features)
# This is for demo purposes and does NOT scale to large data sets. We do
# not use Dataset.from_generator() because that uses tf.py_func which is
# not TPU compatible. The right way to load data is with TFRecordReader.
d = tf.data.Dataset.from_tensor_slices({
"input_ids":
tf.constant(
all_input_ids, shape=[num_examples, seq_length],
dtype=tf.int32),
"input_mask":
tf.constant(
all_input_mask,
shape=[num_examples, seq_length],
dtype=tf.int32),
"segment_ids":
tf.constant(
all_segment_ids,
shape=[num_examples, seq_length],
dtype=tf.int32),
"label_ids":
tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),
})
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)
return d
return input_fn
# This function is not used by this file but is still used by the Colab and
# people who depend on it.
def convert_examples_to_features(examples, label_list, max_seq_length,
tokenizer):
"""Convert a set of `InputExample`s to a list of `InputFeatures`."""
features = []
for (ex_index, example) in enumerate(examples):
if ex_index % 10000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature = convert_single_example(ex_index, example, label_list,
max_seq_length, tokenizer)
features.append(feature)
return features
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"xnli": XnliProcessor,
"tnews": TnewsProcessor,
"afqmc": AFQMCProcessor,
"iflytek": iFLYTEKDataProcessor,
"copa": COPAProcessor,
"cmnli": CMNLIProcessor,
"wsc": WSCProcessor,
"csl": CslProcessor,
"copa": COPAProcessor,
}
tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,
FLAGS.init_checkpoint)
if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:
raise ValueError(
"At least one of `do_train`, `do_eval` or `do_predict' must be True.")
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
if FLAGS.max_seq_length > bert_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, bert_config.max_position_embeddings))
tf.gfile.MakeDirs(FLAGS.output_dir)
task_name = FLAGS.task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
label_list = processor.get_labels()
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = processor.get_train_examples(FLAGS.data_dir)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
model_fn = model_fn_builder(
bert_config=bert_config,
num_labels=len(label_list),
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
if task_name == "inews":
file_based_convert_examples_to_features_for_inews(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
else:
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = file_based_input_fn_builder(
input_file=train_file,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_eval:
# dev dataset
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
num_actual_eval_examples = len(eval_examples)
if FLAGS.use_tpu:
# TPU requires a fixed batch size for all batches, therefore the number
# of examples must be a multiple of the batch size, or else examples
# will get dropped. So we pad with fake examples which are ignored
# later on. These do NOT count towards the metric (all tf.metrics
# support a per-instance weight, and these get a weight of 0.0).
while len(eval_examples) % FLAGS.eval_batch_size != 0:
eval_examples.append(PaddingInputExample())
eval_file = os.path.join(FLAGS.output_dir, "dev.tf_record")
if task_name == "inews":
file_based_convert_examples_to_features_for_inews(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
else:
file_based_convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
len(eval_examples), num_actual_eval_examples,
len(eval_examples) - num_actual_eval_examples)
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
# This tells the estimator to run through the entire set.
eval_steps = None
# However, if running eval on the TPU, you will need to specify the
# number of steps.
if FLAGS.use_tpu:
assert len(eval_examples) % FLAGS.eval_batch_size == 0
eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)
eval_drop_remainder = True if FLAGS.use_tpu else False
eval_input_fn = file_based_input_fn_builder(
input_file=eval_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=eval_drop_remainder)
#######################################################################################################################
# evaluate all checkpoints; you can use the checkpoint with the best dev accuarcy
steps_and_files = []
filenames = tf.gfile.ListDirectory(FLAGS.output_dir)
for filename in filenames:
if filename.endswith(".index"):
ckpt_name = filename[:-6]
cur_filename = os.path.join(FLAGS.output_dir, ckpt_name)
global_step = int(cur_filename.split("-")[-1])
tf.logging.info("Add {} to eval list.".format(cur_filename))
steps_and_files.append([global_step, cur_filename])
steps_and_files = sorted(steps_and_files, key=lambda x: x[0])
output_eval_file = os.path.join(FLAGS.data_dir, "dev_results_roberta_wwm_ext.txt")
print("output_eval_file:", output_eval_file)
tf.logging.info("output_eval_file:" + output_eval_file)
with tf.gfile.GFile(output_eval_file, "w") as writer:
for global_step, filename in sorted(steps_and_files, key=lambda x: x[0]):
result = estimator.evaluate(input_fn=eval_input_fn,
steps=eval_steps, checkpoint_path=filename)
tf.logging.info("***** Eval results %s *****" % (filename))
writer.write("***** Eval results %s *****\n" % (filename))
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
#######################################################################################################################
# result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
#
# output_eval_file = os.path.join(FLAGS.output_dir, "dev_results_roberta_wwm_ext.txt")
# with tf.gfile.GFile(output_eval_file, "w") as writer:
# tf.logging.info("***** Eval results *****")
# for key in sorted(result.keys()):
# tf.logging.info(" %s = %s", key, str(result[key]))
# writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_predict:
predict_examples = processor.get_test_examples(FLAGS.data_dir)
num_actual_predict_examples = len(predict_examples)
if FLAGS.use_tpu:
# TPU requires a fixed batch size for all batches, therefore the number
# of examples must be a multiple of the batch size, or else examples
# will get dropped. So we pad with fake examples which are ignored
# later on.
while len(predict_examples) % FLAGS.predict_batch_size != 0:
predict_examples.append(PaddingInputExample())
predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
if task_name == "inews":
file_based_convert_examples_to_features_for_inews(predict_examples, label_list,
FLAGS.max_seq_length, tokenizer,
predict_file)
else:
file_based_convert_examples_to_features(predict_examples, label_list,
FLAGS.max_seq_length, tokenizer,
predict_file)
tf.logging.info("***** Running prediction*****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
len(predict_examples), num_actual_predict_examples,
len(predict_examples) - num_actual_predict_examples)
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
predict_drop_remainder = True if FLAGS.use_tpu else False
predict_input_fn = file_based_input_fn_builder(
input_file=predict_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=predict_drop_remainder)
result = estimator.predict(input_fn=predict_input_fn)
index2label_map = {}
for (i, label) in enumerate(label_list):
index2label_map[i] = label
output_predict_file_label_name = task_name + "_predict.json"
output_predict_file_label = os.path.join(FLAGS.output_dir, output_predict_file_label_name)
output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
with tf.gfile.GFile(output_predict_file_label, "w") as writer_label:
with tf.gfile.GFile(output_predict_file, "w") as writer:
num_written_lines = 0
tf.logging.info("***** Predict results *****")
for (i, prediction) in enumerate(result):
probabilities = prediction["probabilities"]
label_index = probabilities.argmax(0)
if i >= num_actual_predict_examples:
break
output_line = "\t".join(
str(class_probability)
for class_probability in probabilities) + "\n"
test_label_dict = {}
test_label_dict["id"] = i
test_label_dict["label"] = str(index2label_map[label_index])
if task_name == "tnews":
test_label_dict["label_desc"] = ""
writer.write(output_line)
json.dump(test_label_dict, writer_label)
writer_label.write("\n")
num_written_lines += 1
assert num_written_lines == num_actual_predict_examples
if __name__ == "__main__":
flags.mark_flag_as_required("data_dir")
flags.mark_flag_as_required("task_name")
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| 36,163 | 36.282474 | 123 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/tf_metrics.py | """
Multiclass
from:
https://github.com/guillaumegenthial/tf_metrics/blob/master/tf_metrics/__init__.py
"""
__author__ = "Guillaume Genthial"
import numpy as np
import tensorflow as tf
from tensorflow.python.ops.metrics_impl import _streaming_confusion_matrix
def precision(labels, predictions, num_classes, pos_indices=None,
weights=None, average='micro'):
"""Multi-class precision metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, optional
The indices of the positive classes, default is all
weights : Tensor of tf.int32, optional
Mask, must be of compatible shape with labels
average : str, optional
'micro': counts the total number of true positives, false
positives, and false negatives for the classes in
`pos_indices` and infer the metric from it.
'macro': will compute the metric separately for each class in
`pos_indices` and average. Will not account for class
imbalance.
'weighted': will compute the metric separately for each class in
`pos_indices` and perform a weighted average by the total
number of true labels for each class.
Returns
-------
tuple of (scalar float Tensor, update_op)
"""
cm, op = _streaming_confusion_matrix(
labels, predictions, num_classes, weights)
pr, _, _ = metrics_from_confusion_matrix(
cm, pos_indices, average=average)
op, _, _ = metrics_from_confusion_matrix(
op, pos_indices, average=average)
return (pr, op)
def recall(labels, predictions, num_classes, pos_indices=None, weights=None,
average='micro'):
"""Multi-class recall metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, optional
The indices of the positive classes, default is all
weights : Tensor of tf.int32, optional
Mask, must be of compatible shape with labels
average : str, optional
'micro': counts the total number of true positives, false
positives, and false negatives for the classes in
`pos_indices` and infer the metric from it.
'macro': will compute the metric separately for each class in
`pos_indices` and average. Will not account for class
imbalance.
'weighted': will compute the metric separately for each class in
`pos_indices` and perform a weighted average by the total
number of true labels for each class.
Returns
-------
tuple of (scalar float Tensor, update_op)
"""
cm, op = _streaming_confusion_matrix(
labels, predictions, num_classes, weights)
_, re, _ = metrics_from_confusion_matrix(
cm, pos_indices, average=average)
_, op, _ = metrics_from_confusion_matrix(
op, pos_indices, average=average)
return (re, op)
def f1(labels, predictions, num_classes, pos_indices=None, weights=None,
average='micro'):
return fbeta(labels, predictions, num_classes, pos_indices, weights,
average)
def fbeta(labels, predictions, num_classes, pos_indices=None, weights=None,
average='micro', beta=1):
"""Multi-class fbeta metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, optional
The indices of the positive classes, default is all
weights : Tensor of tf.int32, optional
Mask, must be of compatible shape with labels
average : str, optional
'micro': counts the total number of true positives, false
positives, and false negatives for the classes in
`pos_indices` and infer the metric from it.
'macro': will compute the metric separately for each class in
`pos_indices` and average. Will not account for class
imbalance.
'weighted': will compute the metric separately for each class in
`pos_indices` and perform a weighted average by the total
number of true labels for each class.
beta : int, optional
Weight of precision in harmonic mean
Returns
-------
tuple of (scalar float Tensor, update_op)
"""
cm, op = _streaming_confusion_matrix(
labels, predictions, num_classes, weights)
_, _, fbeta = metrics_from_confusion_matrix(
cm, pos_indices, average=average, beta=beta)
_, _, op = metrics_from_confusion_matrix(
op, pos_indices, average=average, beta=beta)
return (fbeta, op)
def safe_div(numerator, denominator):
"""Safe division, return 0 if denominator is 0"""
numerator, denominator = tf.to_float(numerator), tf.to_float(denominator)
zeros = tf.zeros_like(numerator, dtype=numerator.dtype)
denominator_is_zero = tf.equal(denominator, zeros)
return tf.where(denominator_is_zero, zeros, numerator / denominator)
def pr_re_fbeta(cm, pos_indices, beta=1):
"""Uses a confusion matrix to compute precision, recall and fbeta"""
num_classes = cm.shape[0]
neg_indices = [i for i in range(num_classes) if i not in pos_indices]
cm_mask = np.ones([num_classes, num_classes])
cm_mask[neg_indices, neg_indices] = 0
diag_sum = tf.reduce_sum(tf.diag_part(cm * cm_mask))
cm_mask = np.ones([num_classes, num_classes])
cm_mask[:, neg_indices] = 0
tot_pred = tf.reduce_sum(cm * cm_mask)
cm_mask = np.ones([num_classes, num_classes])
cm_mask[neg_indices, :] = 0
tot_gold = tf.reduce_sum(cm * cm_mask)
pr = safe_div(diag_sum, tot_pred)
re = safe_div(diag_sum, tot_gold)
fbeta = safe_div((1. + beta**2) * pr * re, beta**2 * pr + re)
return pr, re, fbeta
def metrics_from_confusion_matrix(cm, pos_indices=None, average='micro',
beta=1):
"""Precision, Recall and F1 from the confusion matrix
Parameters
----------
cm : tf.Tensor of type tf.int32, of shape (num_classes, num_classes)
The streaming confusion matrix.
pos_indices : list of int, optional
The indices of the positive classes
beta : int, optional
Weight of precision in harmonic mean
average : str, optional
'micro', 'macro' or 'weighted'
"""
num_classes = cm.shape[0]
if pos_indices is None:
pos_indices = [i for i in range(num_classes)]
if average == 'micro':
return pr_re_fbeta(cm, pos_indices, beta)
elif average in {'macro', 'weighted'}:
precisions, recalls, fbetas, n_golds = [], [], [], []
for idx in pos_indices:
pr, re, fbeta = pr_re_fbeta(cm, [idx], beta)
precisions.append(pr)
recalls.append(re)
fbetas.append(fbeta)
cm_mask = np.zeros([num_classes, num_classes])
cm_mask[idx, :] = 1
n_golds.append(tf.to_float(tf.reduce_sum(cm * cm_mask)))
if average == 'macro':
pr = tf.reduce_mean(precisions)
re = tf.reduce_mean(recalls)
fbeta = tf.reduce_mean(fbetas)
return pr, re, fbeta
if average == 'weighted':
n_gold = tf.reduce_sum(n_golds)
pr_sum = sum(p * n for p, n in zip(precisions, n_golds))
pr = safe_div(pr_sum, n_gold)
re_sum = sum(r * n for r, n in zip(recalls, n_golds))
re = safe_div(re_sum, n_gold)
fbeta_sum = sum(f * n for f, n in zip(fbetas, n_golds))
fbeta = safe_div(fbeta_sum, n_gold)
return pr, re, fbeta
else:
raise NotImplementedError() | 8,188 | 37.088372 | 82 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/tokenization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tokenization classes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import re
import unicodedata
import six
import tensorflow as tf
def validate_case_matches_checkpoint(do_lower_case, init_checkpoint):
"""Checks whether the casing config is consistent with the checkpoint name."""
# The casing has to be passed in by the user and there is no explicit check
# as to whether it matches the checkpoint. The casing information probably
# should have been stored in the bert_config.json file, but it's not, so
# we have to heuristically detect it to validate.
if not init_checkpoint:
return
m = re.match("^.*?([A-Za-z0-9_-]+)/bert_model.ckpt", init_checkpoint)
if m is None:
return
model_name = m.group(1)
lower_models = [
"uncased_L-24_H-1024_A-16", "uncased_L-12_H-768_A-12",
"multilingual_L-12_H-768_A-12", "chinese_L-12_H-768_A-12"
]
cased_models = [
"cased_L-12_H-768_A-12", "cased_L-24_H-1024_A-16",
"multi_cased_L-12_H-768_A-12"
]
is_bad_config = False
if model_name in lower_models and not do_lower_case:
is_bad_config = True
actual_flag = "False"
case_name = "lowercased"
opposite_flag = "True"
if model_name in cased_models and do_lower_case:
is_bad_config = True
actual_flag = "True"
case_name = "cased"
opposite_flag = "False"
if is_bad_config:
raise ValueError(
"You passed in `--do_lower_case=%s` with `--init_checkpoint=%s`. "
"However, `%s` seems to be a %s model, so you "
"should pass in `--do_lower_case=%s` so that the fine-tuning matches "
"how the model was pre-training. If this error is wrong, please "
"just comment out this check." % (actual_flag, init_checkpoint,
model_name, case_name, opposite_flag))
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text.decode("utf-8", "ignore")
elif isinstance(text, unicode):
return text
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?")
def printable_text(text):
"""Returns text encoded in a way suitable for print or `tf.logging`."""
# These functions want `str` for both Python2 and Python3, but in one case
# it's a Unicode string and in the other it's a byte string.
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text
elif isinstance(text, unicode):
return text.encode("utf-8")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?")
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
index = 0
with tf.gfile.GFile(vocab_file, "r") as reader:
while True:
token = convert_to_unicode(reader.readline())
if not token:
break
token = token.strip()
vocab[token] = index
index += 1
return vocab
def convert_by_vocab(vocab, items):
"""Converts a sequence of [tokens|ids] using the vocab."""
output = []
for item in items:
output.append(vocab[item])
return output
def convert_tokens_to_ids(vocab, tokens):
return convert_by_vocab(vocab, tokens)
def convert_ids_to_tokens(inv_vocab, ids):
return convert_by_vocab(inv_vocab, ids)
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens
class FullTokenizer(object):
"""Runs end-to-end tokenziation."""
def __init__(self, vocab_file, do_lower_case=True):
self.vocab = load_vocab(vocab_file)
self.inv_vocab = {v: k for k, v in self.vocab.items()}
self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
def tokenize(self, text):
split_tokens = []
for token in self.basic_tokenizer.tokenize(text):
for sub_token in self.wordpiece_tokenizer.tokenize(token):
split_tokens.append(sub_token)
return split_tokens
def convert_tokens_to_ids(self, tokens):
return convert_by_vocab(self.vocab, tokens)
def convert_ids_to_tokens(self, ids):
return convert_by_vocab(self.inv_vocab, ids)
class BasicTokenizer(object):
"""Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
def __init__(self, do_lower_case=True):
"""Constructs a BasicTokenizer.
Args:
do_lower_case: Whether to lower case the input.
"""
self.do_lower_case = do_lower_case
def tokenize(self, text):
"""Tokenizes a piece of text."""
text = convert_to_unicode(text)
text = self._clean_text(text)
# This was added on November 1st, 2018 for the multilingual and Chinese
# models. This is also applied to the English models now, but it doesn't
# matter since the English models were not trained on any Chinese data
# and generally don't have any Chinese data in them (there are Chinese
# characters in the vocabulary because Wikipedia does have some Chinese
# words in the English Wikipedia.).
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if self.do_lower_case:
token = token.lower()
token = self._run_strip_accents(token)
split_tokens.extend(self._run_split_on_punc(token))
output_tokens = whitespace_tokenize(" ".join(split_tokens))
return output_tokens
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output)
def _run_split_on_punc(self, text):
"""Splits punctuation on a piece of text."""
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return ["".join(x) for x in output]
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output)
def _is_chinese_char(self, cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
(cp >= 0x3400 and cp <= 0x4DBF) or #
(cp >= 0x20000 and cp <= 0x2A6DF) or #
(cp >= 0x2A700 and cp <= 0x2B73F) or #
(cp >= 0x2B740 and cp <= 0x2B81F) or #
(cp >= 0x2B820 and cp <= 0x2CEAF) or
(cp >= 0xF900 and cp <= 0xFAFF) or #
(cp >= 0x2F800 and cp <= 0x2FA1F)): #
return True
return False
def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp == 0 or cp == 0xfffd or _is_control(char):
continue
if _is_whitespace(char):
output.append(" ")
else:
output.append(char)
return "".join(output)
class WordpieceTokenizer(object):
"""Runs WordPiece tokenziation."""
def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=200):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through `BasicTokenizer.
Returns:
A list of wordpiece tokens.
"""
text = convert_to_unicode(text)
output_tokens = []
for token in whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens
def _is_whitespace(char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
cat = unicodedata.category(char)
if cat == "Zs":
return True
return False
def _is_control(char):
"""Checks whether `chars` is a control character."""
# These are technically control characters but we count them as whitespace
# characters.
if char == "\t" or char == "\n" or char == "\r":
return False
cat = unicodedata.category(char)
if cat in ("Cc", "Cf"):
return True
return False
def _is_punctuation(char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, for
# consistency.
if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
(cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
return True
cat = unicodedata.category(char)
if cat.startswith("P"):
return True
return False
| 12,257 | 29.645 | 80 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/modeling.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The main BERT model and related functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import json
import math
import re
import numpy as np
import six
import tensorflow as tf
class BertConfig(object):
"""Configuration for `BertModel`."""
def __init__(self,
vocab_size,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=16,
initializer_range=0.02):
"""Constructs BertConfig.
Args:
vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.
hidden_size: Size of the encoder layers and the pooler layer.
num_hidden_layers: Number of hidden layers in the Transformer encoder.
num_attention_heads: Number of attention heads for each attention layer in
the Transformer encoder.
intermediate_size: The size of the "intermediate" (i.e., feed-forward)
layer in the Transformer encoder.
hidden_act: The non-linear activation function (function or string) in the
encoder and pooler.
hidden_dropout_prob: The dropout probability for all fully connected
layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob: The dropout ratio for the attention
probabilities.
max_position_embeddings: The maximum sequence length that this model might
ever be used with. Typically set this to something large just in case
(e.g., 512 or 1024 or 2048).
type_vocab_size: The vocabulary size of the `token_type_ids` passed into
`BertModel`.
initializer_range: The stdev of the truncated_normal_initializer for
initializing all weight matrices.
"""
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
@classmethod
def from_dict(cls, json_object):
"""Constructs a `BertConfig` from a Python dictionary of parameters."""
config = BertConfig(vocab_size=None)
for (key, value) in six.iteritems(json_object):
config.__dict__[key] = value
return config
@classmethod
def from_json_file(cls, json_file):
"""Constructs a `BertConfig` from a json file of parameters."""
with tf.gfile.GFile(json_file, "r") as reader:
text = reader.read()
return cls.from_dict(json.loads(text))
def to_dict(self):
"""Serializes this instance to a Python dictionary."""
output = copy.deepcopy(self.__dict__)
return output
def to_json_string(self):
"""Serializes this instance to a JSON string."""
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
class BertModel(object):
"""BERT model ("Bidirectional Encoder Representations from Transformers").
Example usage:
```python
# Already been converted into WordPiece token ids
input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])
input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])
token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]])
config = modeling.BertConfig(vocab_size=32000, hidden_size=512,
num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)
model = modeling.BertModel(config=config, is_training=True,
input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)
label_embeddings = tf.get_variable(...)
pooled_output = model.get_pooled_output()
logits = tf.matmul(pooled_output, label_embeddings)
...
```
"""
def __init__(self,
config,
is_training,
input_ids,
input_mask=None,
token_type_ids=None,
use_one_hot_embeddings=False,
scope=None):
"""Constructor for BertModel.
Args:
config: `BertConfig` instance.
is_training: bool. true for training model, false for eval model. Controls
whether dropout will be applied.
input_ids: int32 Tensor of shape [batch_size, seq_length].
input_mask: (optional) int32 Tensor of shape [batch_size, seq_length].
token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
use_one_hot_embeddings: (optional) bool. Whether to use one-hot word
embeddings or tf.embedding_lookup() for the word embeddings.
scope: (optional) variable scope. Defaults to "bert".
Raises:
ValueError: The config is invalid or one of the input tensor shapes
is invalid.
"""
config = copy.deepcopy(config)
if not is_training:
config.hidden_dropout_prob = 0.0
config.attention_probs_dropout_prob = 0.0
input_shape = get_shape_list(input_ids, expected_rank=2)
batch_size = input_shape[0]
seq_length = input_shape[1]
if input_mask is None:
input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)
if token_type_ids is None:
token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)
with tf.variable_scope(scope, default_name="bert"):
with tf.variable_scope("embeddings"):
# Perform embedding lookup on the word ids.
(self.embedding_output, self.embedding_table) = embedding_lookup(
input_ids=input_ids,
vocab_size=config.vocab_size,
embedding_size=config.hidden_size,
initializer_range=config.initializer_range,
word_embedding_name="word_embeddings",
use_one_hot_embeddings=use_one_hot_embeddings)
# Add positional embeddings and token type embeddings, then layer
# normalize and perform dropout.
self.embedding_output = embedding_postprocessor(
input_tensor=self.embedding_output,
use_token_type=True,
token_type_ids=token_type_ids,
token_type_vocab_size=config.type_vocab_size,
token_type_embedding_name="token_type_embeddings",
use_position_embeddings=True,
position_embedding_name="position_embeddings",
initializer_range=config.initializer_range,
max_position_embeddings=config.max_position_embeddings,
dropout_prob=config.hidden_dropout_prob)
with tf.variable_scope("encoder"):
# This converts a 2D mask of shape [batch_size, seq_length] to a 3D
# mask of shape [batch_size, seq_length, seq_length] which is used
# for the attention scores.
attention_mask = create_attention_mask_from_input_mask(
input_ids, input_mask)
# Run the stacked transformer.
# `sequence_output` shape = [batch_size, seq_length, hidden_size].
self.all_encoder_layers = transformer_model(
input_tensor=self.embedding_output,
attention_mask=attention_mask,
hidden_size=config.hidden_size,
num_hidden_layers=config.num_hidden_layers,
num_attention_heads=config.num_attention_heads,
intermediate_size=config.intermediate_size,
intermediate_act_fn=get_activation(config.hidden_act),
hidden_dropout_prob=config.hidden_dropout_prob,
attention_probs_dropout_prob=config.attention_probs_dropout_prob,
initializer_range=config.initializer_range,
do_return_all_layers=True)
self.sequence_output = self.all_encoder_layers[-1]
# The "pooler" converts the encoded sequence tensor of shape
# [batch_size, seq_length, hidden_size] to a tensor of shape
# [batch_size, hidden_size]. This is necessary for segment-level
# (or segment-pair-level) classification tasks where we need a fixed
# dimensional representation of the segment.
with tf.variable_scope("pooler"):
# We "pool" the model by simply taking the hidden state corresponding
# to the first token. We assume that this has been pre-trained
first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)
self.pooled_output = tf.layers.dense(
first_token_tensor,
config.hidden_size,
activation=tf.tanh,
kernel_initializer=create_initializer(config.initializer_range))
def get_pooled_output(self):
return self.pooled_output
def get_sequence_output(self):
"""Gets final hidden layer of encoder.
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size] corresponding
to the final hidden of the transformer encoder.
"""
return self.sequence_output
def get_all_encoder_layers(self):
return self.all_encoder_layers
def get_embedding_output(self):
"""Gets output of the embedding lookup (i.e., input to the transformer).
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size] corresponding
to the output of the embedding layer, after summing the word
embeddings with the positional embeddings and the token type embeddings,
then performing layer normalization. This is the input to the transformer.
"""
return self.embedding_output
def get_embedding_table(self):
return self.embedding_table
def gelu(x):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
`x` with the GELU activation applied.
"""
cdf = 0.5 * (1.0 + tf.tanh(
(np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
return x * cdf
def get_activation(activation_string):
"""Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
Args:
activation_string: String name of the activation function.
Returns:
A Python function corresponding to the activation function. If
`activation_string` is None, empty, or "linear", this will return None.
If `activation_string` is not a string, it will return `activation_string`.
Raises:
ValueError: The `activation_string` does not correspond to a known
activation.
"""
# We assume that anything that"s not a string is already an activation
# function, so we just return it.
if not isinstance(activation_string, six.string_types):
return activation_string
if not activation_string:
return None
act = activation_string.lower()
if act == "linear":
return None
elif act == "relu":
return tf.nn.relu
elif act == "gelu":
return gelu
elif act == "tanh":
return tf.tanh
else:
raise ValueError("Unsupported activation: %s" % act)
def get_assignment_map_from_checkpoint(tvars, init_checkpoint):
"""Compute the union of the current variables and checkpoint variables."""
assignment_map = {}
initialized_variable_names = {}
name_to_variable = collections.OrderedDict()
for var in tvars:
name = var.name
m = re.match("^(.*):\\d+$", name)
if m is not None:
name = m.group(1)
name_to_variable[name] = var
init_vars = tf.train.list_variables(init_checkpoint)
assignment_map = collections.OrderedDict()
for x in init_vars:
(name, var) = (x[0], x[1])
if name not in name_to_variable:
continue
assignment_map[name] = name
initialized_variable_names[name] = 1
initialized_variable_names[name + ":0"] = 1
return (assignment_map, initialized_variable_names)
def dropout(input_tensor, dropout_prob):
"""Perform dropout.
Args:
input_tensor: float Tensor.
dropout_prob: Python float. The probability of dropping out a value (NOT of
*keeping* a dimension as in `tf.nn.dropout`).
Returns:
A version of `input_tensor` with dropout applied.
"""
if dropout_prob is None or dropout_prob == 0.0:
return input_tensor
output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)
return output
def layer_norm(input_tensor, name=None):
"""Run layer normalization on the last dimension of the tensor."""
return tf.contrib.layers.layer_norm(
inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
"""Runs layer normalization followed by dropout."""
output_tensor = layer_norm(input_tensor, name)
output_tensor = dropout(output_tensor, dropout_prob)
return output_tensor
def create_initializer(initializer_range=0.02):
"""Creates a `truncated_normal_initializer` with the given range."""
return tf.truncated_normal_initializer(stddev=initializer_range)
def embedding_lookup(input_ids,
vocab_size,
embedding_size=128,
initializer_range=0.02,
word_embedding_name="word_embeddings",
use_one_hot_embeddings=False):
"""Looks up words embeddings for id tensor.
Args:
input_ids: int32 Tensor of shape [batch_size, seq_length] containing word
ids.
vocab_size: int. Size of the embedding vocabulary.
embedding_size: int. Width of the word embeddings.
initializer_range: float. Embedding initialization range.
word_embedding_name: string. Name of the embedding table.
use_one_hot_embeddings: bool. If True, use one-hot method for word
embeddings. If False, use `tf.gather()`.
Returns:
float Tensor of shape [batch_size, seq_length, embedding_size].
"""
# This function assumes that the input is of shape [batch_size, seq_length,
# num_inputs].
#
# If the input is a 2D tensor of shape [batch_size, seq_length], we
# reshape to [batch_size, seq_length, 1].
if input_ids.shape.ndims == 2:
input_ids = tf.expand_dims(input_ids, axis=[-1])
embedding_table = tf.get_variable(
name=word_embedding_name,
shape=[vocab_size, embedding_size],
initializer=create_initializer(initializer_range))
flat_input_ids = tf.reshape(input_ids, [-1])
if use_one_hot_embeddings:
one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)
output = tf.matmul(one_hot_input_ids, embedding_table)
else:
output = tf.gather(embedding_table, flat_input_ids)
input_shape = get_shape_list(input_ids)
output = tf.reshape(output,
input_shape[0:-1] + [input_shape[-1] * embedding_size])
return (output, embedding_table)
def embedding_postprocessor(input_tensor,
use_token_type=False,
token_type_ids=None,
token_type_vocab_size=16,
token_type_embedding_name="token_type_embeddings",
use_position_embeddings=True,
position_embedding_name="position_embeddings",
initializer_range=0.02,
max_position_embeddings=512,
dropout_prob=0.1):
"""Performs various post-processing on a word embedding tensor.
Args:
input_tensor: float Tensor of shape [batch_size, seq_length,
embedding_size].
use_token_type: bool. Whether to add embeddings for `token_type_ids`.
token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
Must be specified if `use_token_type` is True.
token_type_vocab_size: int. The vocabulary size of `token_type_ids`.
token_type_embedding_name: string. The name of the embedding table variable
for token type ids.
use_position_embeddings: bool. Whether to add position embeddings for the
position of each token in the sequence.
position_embedding_name: string. The name of the embedding table variable
for positional embeddings.
initializer_range: float. Range of the weight initialization.
max_position_embeddings: int. Maximum sequence length that might ever be
used with this model. This can be longer than the sequence length of
input_tensor, but cannot be shorter.
dropout_prob: float. Dropout probability applied to the final output tensor.
Returns:
float tensor with same shape as `input_tensor`.
Raises:
ValueError: One of the tensor shapes or input values is invalid.
"""
input_shape = get_shape_list(input_tensor, expected_rank=3)
batch_size = input_shape[0]
seq_length = input_shape[1]
width = input_shape[2]
output = input_tensor
if use_token_type:
if token_type_ids is None:
raise ValueError("`token_type_ids` must be specified if"
"`use_token_type` is True.")
token_type_table = tf.get_variable(
name=token_type_embedding_name,
shape=[token_type_vocab_size, width],
initializer=create_initializer(initializer_range))
# This vocab will be small so we always do one-hot here, since it is always
# faster for a small vocabulary.
flat_token_type_ids = tf.reshape(token_type_ids, [-1])
one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)
token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)
token_type_embeddings = tf.reshape(token_type_embeddings,
[batch_size, seq_length, width])
output += token_type_embeddings
if use_position_embeddings:
assert_op = tf.assert_less_equal(seq_length, max_position_embeddings)
with tf.control_dependencies([assert_op]):
full_position_embeddings = tf.get_variable(
name=position_embedding_name,
shape=[max_position_embeddings, width],
initializer=create_initializer(initializer_range))
# Since the position embedding table is a learned variable, we create it
# using a (long) sequence length `max_position_embeddings`. The actual
# sequence length might be shorter than this, for faster training of
# tasks that do not have long sequences.
#
# So `full_position_embeddings` is effectively an embedding table
# for position [0, 1, 2, ..., max_position_embeddings-1], and the current
# sequence has positions [0, 1, 2, ... seq_length-1], so we can just
# perform a slice.
position_embeddings = tf.slice(full_position_embeddings, [0, 0],
[seq_length, -1])
num_dims = len(output.shape.as_list())
# Only the last two dimensions are relevant (`seq_length` and `width`), so
# we broadcast among the first dimensions, which is typically just
# the batch size.
position_broadcast_shape = []
for _ in range(num_dims - 2):
position_broadcast_shape.append(1)
position_broadcast_shape.extend([seq_length, width])
position_embeddings = tf.reshape(position_embeddings,
position_broadcast_shape)
output += position_embeddings
output = layer_norm_and_dropout(output, dropout_prob)
return output
def create_attention_mask_from_input_mask(from_tensor, to_mask):
"""Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Tensor of shape [batch_size, from_seq_length, to_seq_length].
"""
from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
batch_size = from_shape[0]
from_seq_length = from_shape[1]
to_shape = get_shape_list(to_mask, expected_rank=2)
to_seq_length = to_shape[1]
to_mask = tf.cast(
tf.reshape(to_mask, [batch_size, 1, to_seq_length]), tf.float32)
# We don't assume that `from_tensor` is a mask (although it could be). We
# don't actually care if we attend *from* padding tokens (only *to* padding)
# tokens so we create a tensor of all ones.
#
# `broadcast_ones` = [batch_size, from_seq_length, 1]
broadcast_ones = tf.ones(
shape=[batch_size, from_seq_length, 1], dtype=tf.float32)
# Here we broadcast along two dimensions to create the mask.
mask = broadcast_ones * to_mask
return mask
def attention_layer(from_tensor,
to_tensor,
attention_mask=None,
num_attention_heads=1,
size_per_head=512,
query_act=None,
key_act=None,
value_act=None,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
do_return_2d_tensor=False,
batch_size=None,
from_seq_length=None,
to_seq_length=None):
"""Performs multi-headed attention from `from_tensor` to `to_tensor`.
This is an implementation of multi-headed attention based on "Attention
is all you Need". If `from_tensor` and `to_tensor` are the same, then
this is self-attention. Each timestep in `from_tensor` attends to the
corresponding sequence in `to_tensor`, and returns a fixed-with vector.
This function first projects `from_tensor` into a "query" tensor and
`to_tensor` into "key" and "value" tensors. These are (effectively) a list
of tensors of length `num_attention_heads`, where each tensor is of shape
[batch_size, seq_length, size_per_head].
Then, the query and key tensors are dot-producted and scaled. These are
softmaxed to obtain attention probabilities. The value tensors are then
interpolated by these probabilities, then concatenated back to a single
tensor and returned.
In practice, the multi-headed attention are done with transposes and
reshapes rather than actual separate tensors.
Args:
from_tensor: float Tensor of shape [batch_size, from_seq_length,
from_width].
to_tensor: float Tensor of shape [batch_size, to_seq_length, to_width].
attention_mask: (optional) int32 Tensor of shape [batch_size,
from_seq_length, to_seq_length]. The values should be 1 or 0. The
attention scores will effectively be set to -infinity for any positions in
the mask that are 0, and will be unchanged for positions that are 1.
num_attention_heads: int. Number of attention heads.
size_per_head: int. Size of each attention head.
query_act: (optional) Activation function for the query transform.
key_act: (optional) Activation function for the key transform.
value_act: (optional) Activation function for the value transform.
attention_probs_dropout_prob: (optional) float. Dropout probability of the
attention probabilities.
initializer_range: float. Range of the weight initializer.
do_return_2d_tensor: bool. If True, the output will be of shape [batch_size
* from_seq_length, num_attention_heads * size_per_head]. If False, the
output will be of shape [batch_size, from_seq_length, num_attention_heads
* size_per_head].
batch_size: (Optional) int. If the input is 2D, this might be the batch size
of the 3D version of the `from_tensor` and `to_tensor`.
from_seq_length: (Optional) If the input is 2D, this might be the seq length
of the 3D version of the `from_tensor`.
to_seq_length: (Optional) If the input is 2D, this might be the seq length
of the 3D version of the `to_tensor`.
Returns:
float Tensor of shape [batch_size, from_seq_length,
num_attention_heads * size_per_head]. (If `do_return_2d_tensor` is
true, this will be of shape [batch_size * from_seq_length,
num_attention_heads * size_per_head]).
Raises:
ValueError: Any of the arguments or tensor shapes are invalid.
"""
def transpose_for_scores(input_tensor, batch_size, num_attention_heads,
seq_length, width):
output_tensor = tf.reshape(
input_tensor, [batch_size, seq_length, num_attention_heads, width])
output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])
return output_tensor
from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])
if len(from_shape) != len(to_shape):
raise ValueError(
"The rank of `from_tensor` must match the rank of `to_tensor`.")
if len(from_shape) == 3:
batch_size = from_shape[0]
from_seq_length = from_shape[1]
to_seq_length = to_shape[1]
elif len(from_shape) == 2:
if (batch_size is None or from_seq_length is None or to_seq_length is None):
raise ValueError(
"When passing in rank 2 tensors to attention_layer, the values "
"for `batch_size`, `from_seq_length`, and `to_seq_length` "
"must all be specified.")
# Scalar dimensions referenced here:
# B = batch size (number of sequences)
# F = `from_tensor` sequence length
# T = `to_tensor` sequence length
# N = `num_attention_heads`
# H = `size_per_head`
from_tensor_2d = reshape_to_matrix(from_tensor)
to_tensor_2d = reshape_to_matrix(to_tensor)
# `query_layer` = [B*F, N*H]
query_layer = tf.layers.dense(
from_tensor_2d,
num_attention_heads * size_per_head,
activation=query_act,
name="query",
kernel_initializer=create_initializer(initializer_range))
# `key_layer` = [B*T, N*H]
key_layer = tf.layers.dense(
to_tensor_2d,
num_attention_heads * size_per_head,
activation=key_act,
name="key",
kernel_initializer=create_initializer(initializer_range))
# `value_layer` = [B*T, N*H]
value_layer = tf.layers.dense(
to_tensor_2d,
num_attention_heads * size_per_head,
activation=value_act,
name="value",
kernel_initializer=create_initializer(initializer_range))
# `query_layer` = [B, N, F, H]
query_layer = transpose_for_scores(query_layer, batch_size,
num_attention_heads, from_seq_length,
size_per_head)
# `key_layer` = [B, N, T, H]
key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,
to_seq_length, size_per_head)
# Take the dot product between "query" and "key" to get the raw
# attention scores.
# `attention_scores` = [B, N, F, T]
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
attention_scores = tf.multiply(attention_scores,
1.0 / math.sqrt(float(size_per_head)))
if attention_mask is not None:
# `attention_mask` = [B, 1, F, T]
attention_mask = tf.expand_dims(attention_mask, axis=[1])
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
adder = (1.0 - tf.cast(attention_mask, tf.float32)) * -10000.0
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
attention_scores += adder
# Normalize the attention scores to probabilities.
# `attention_probs` = [B, N, F, T]
attention_probs = tf.nn.softmax(attention_scores)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = dropout(attention_probs, attention_probs_dropout_prob)
# `value_layer` = [B, T, N, H]
value_layer = tf.reshape(
value_layer,
[batch_size, to_seq_length, num_attention_heads, size_per_head])
# `value_layer` = [B, N, T, H]
value_layer = tf.transpose(value_layer, [0, 2, 1, 3])
# `context_layer` = [B, N, F, H]
context_layer = tf.matmul(attention_probs, value_layer)
# `context_layer` = [B, F, N, H]
context_layer = tf.transpose(context_layer, [0, 2, 1, 3])
if do_return_2d_tensor:
# `context_layer` = [B*F, N*H]
context_layer = tf.reshape(
context_layer,
[batch_size * from_seq_length, num_attention_heads * size_per_head])
else:
# `context_layer` = [B, F, N*H]
context_layer = tf.reshape(
context_layer,
[batch_size, from_seq_length, num_attention_heads * size_per_head])
return context_layer
def transformer_model(input_tensor,
attention_mask=None,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
intermediate_act_fn=gelu,
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
initializer_range=0.02,
do_return_all_layers=False):
"""Multi-headed, multi-layer Transformer from "Attention is All You Need".
This is almost an exact implementation of the original Transformer encoder.
See the original paper:
https://arxiv.org/abs/1706.03762
Also see:
https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py
Args:
input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].
attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length,
seq_length], with 1 for positions that can be attended to and 0 in
positions that should not be.
hidden_size: int. Hidden size of the Transformer.
num_hidden_layers: int. Number of layers (blocks) in the Transformer.
num_attention_heads: int. Number of attention heads in the Transformer.
intermediate_size: int. The size of the "intermediate" (a.k.a., feed
forward) layer.
intermediate_act_fn: function. The non-linear activation function to apply
to the output of the intermediate/feed-forward layer.
hidden_dropout_prob: float. Dropout probability for the hidden layers.
attention_probs_dropout_prob: float. Dropout probability of the attention
probabilities.
initializer_range: float. Range of the initializer (stddev of truncated
normal).
do_return_all_layers: Whether to also return all layers or just the final
layer.
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size], the final
hidden layer of the Transformer.
Raises:
ValueError: A Tensor shape or parameter is invalid.
"""
if hidden_size % num_attention_heads != 0:
raise ValueError(
"The hidden size (%d) is not a multiple of the number of attention "
"heads (%d)" % (hidden_size, num_attention_heads))
attention_head_size = int(hidden_size / num_attention_heads)
input_shape = get_shape_list(input_tensor, expected_rank=3)
batch_size = input_shape[0]
seq_length = input_shape[1]
input_width = input_shape[2]
# The Transformer performs sum residuals on all layers so the input needs
# to be the same as the hidden size.
if input_width != hidden_size:
raise ValueError("The width of the input tensor (%d) != hidden size (%d)" %
(input_width, hidden_size))
# We keep the representation as a 2D tensor to avoid re-shaping it back and
# forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on
# the GPU/CPU but may not be free on the TPU, so we want to minimize them to
# help the optimizer.
prev_output = reshape_to_matrix(input_tensor)
all_layer_outputs = []
for layer_idx in range(num_hidden_layers):
with tf.variable_scope("layer_%d" % layer_idx):
layer_input = prev_output
with tf.variable_scope("attention"):
attention_heads = []
with tf.variable_scope("self"):
attention_head = attention_layer(
from_tensor=layer_input,
to_tensor=layer_input,
attention_mask=attention_mask,
num_attention_heads=num_attention_heads,
size_per_head=attention_head_size,
attention_probs_dropout_prob=attention_probs_dropout_prob,
initializer_range=initializer_range,
do_return_2d_tensor=True,
batch_size=batch_size,
from_seq_length=seq_length,
to_seq_length=seq_length)
attention_heads.append(attention_head)
attention_output = None
if len(attention_heads) == 1:
attention_output = attention_heads[0]
else:
# In the case where we have other sequences, we just concatenate
# them to the self-attention head before the projection.
attention_output = tf.concat(attention_heads, axis=-1)
# Run a linear projection of `hidden_size` then add a residual
# with `layer_input`.
with tf.variable_scope("output"):
attention_output = tf.layers.dense(
attention_output,
hidden_size,
kernel_initializer=create_initializer(initializer_range))
attention_output = dropout(attention_output, hidden_dropout_prob)
attention_output = layer_norm(attention_output + layer_input)
# The activation is only applied to the "intermediate" hidden layer.
with tf.variable_scope("intermediate"):
intermediate_output = tf.layers.dense(
attention_output,
intermediate_size,
activation=intermediate_act_fn,
kernel_initializer=create_initializer(initializer_range))
# Down-project back to `hidden_size` then add the residual.
with tf.variable_scope("output"):
layer_output = tf.layers.dense(
intermediate_output,
hidden_size,
kernel_initializer=create_initializer(initializer_range))
layer_output = dropout(layer_output, hidden_dropout_prob)
layer_output = layer_norm(layer_output + attention_output)
prev_output = layer_output
all_layer_outputs.append(layer_output)
if do_return_all_layers:
final_outputs = []
for layer_output in all_layer_outputs:
final_output = reshape_from_matrix(layer_output, input_shape)
final_outputs.append(final_output)
return final_outputs
else:
final_output = reshape_from_matrix(prev_output, input_shape)
return final_output
def get_shape_list(tensor, expected_rank=None, name=None):
"""Returns a list of the shape of tensor, preferring static dimensions.
Args:
tensor: A tf.Tensor object to find the shape of.
expected_rank: (optional) int. The expected rank of `tensor`. If this is
specified and the `tensor` has a different rank, and exception will be
thrown.
name: Optional name of the tensor for the error message.
Returns:
A list of dimensions of the shape of tensor. All static dimensions will
be returned as python integers, and dynamic dimensions will be returned
as tf.Tensor scalars.
"""
if name is None:
name = tensor.name
if expected_rank is not None:
assert_rank(tensor, expected_rank, name)
shape = tensor.shape.as_list()
non_static_indexes = []
for (index, dim) in enumerate(shape):
if dim is None:
non_static_indexes.append(index)
if not non_static_indexes:
return shape
dyn_shape = tf.shape(tensor)
for index in non_static_indexes:
shape[index] = dyn_shape[index]
return shape
def reshape_to_matrix(input_tensor):
"""Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix)."""
ndims = input_tensor.shape.ndims
if ndims < 2:
raise ValueError("Input tensor must have at least rank 2. Shape = %s" %
(input_tensor.shape))
if ndims == 2:
return input_tensor
width = input_tensor.shape[-1]
output_tensor = tf.reshape(input_tensor, [-1, width])
return output_tensor
def reshape_from_matrix(output_tensor, orig_shape_list):
"""Reshapes a rank 2 tensor back to its original rank >= 2 tensor."""
if len(orig_shape_list) == 2:
return output_tensor
output_shape = get_shape_list(output_tensor)
orig_dims = orig_shape_list[0:-1]
width = output_shape[-1]
return tf.reshape(output_tensor, orig_dims + [width])
def assert_rank(tensor, expected_rank, name=None):
"""Raises an exception if the tensor rank is not of the expected rank.
Args:
tensor: A tf.Tensor to check the rank of.
expected_rank: Python integer or list of integers, expected rank.
name: Optional name of the tensor for the error message.
Raises:
ValueError: If the expected shape doesn't match the actual shape.
"""
if name is None:
name = tensor.name
expected_rank_dict = {}
if isinstance(expected_rank, six.integer_types):
expected_rank_dict[expected_rank] = True
else:
for x in expected_rank:
expected_rank_dict[x] = True
actual_rank = tensor.shape.ndims
if actual_rank not in expected_rank_dict:
scope_name = tf.get_variable_scope().name
raise ValueError(
"For the tensor `%s` in scope `%s`, the actual rank "
"`%d` (shape = %s) is not equal to the expected rank `%s`" %
(name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))
| 37,922 | 37.422492 | 93 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/extract_features.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Extract pre-computed feature vectors from BERT."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import codecs
import collections
import json
import re
import modeling
import tokenization
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_string("input_file", None, "")
flags.DEFINE_string("output_file", None, "")
flags.DEFINE_string("layers", "-1,-2,-3,-4", "")
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_integer(
"max_seq_length", 128,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded.")
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_integer("batch_size", 32, "Batch size for predictions.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
flags.DEFINE_string("master", None,
"If using a TPU, the address of the master.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
flags.DEFINE_bool(
"use_one_hot_embeddings", False,
"If True, tf.one_hot will be used for embedding lookups, otherwise "
"tf.nn.embedding_lookup will be used. On TPUs, this should be True "
"since it is much faster.")
class InputExample(object):
def __init__(self, unique_id, text_a, text_b):
self.unique_id = unique_id
self.text_a = text_a
self.text_b = text_b
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids):
self.unique_id = unique_id
self.tokens = tokens
self.input_ids = input_ids
self.input_mask = input_mask
self.input_type_ids = input_type_ids
def input_fn_builder(features, seq_length):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
all_unique_ids = []
all_input_ids = []
all_input_mask = []
all_input_type_ids = []
for feature in features:
all_unique_ids.append(feature.unique_id)
all_input_ids.append(feature.input_ids)
all_input_mask.append(feature.input_mask)
all_input_type_ids.append(feature.input_type_ids)
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
num_examples = len(features)
# This is for demo purposes and does NOT scale to large data sets. We do
# not use Dataset.from_generator() because that uses tf.py_func which is
# not TPU compatible. The right way to load data is with TFRecordReader.
d = tf.data.Dataset.from_tensor_slices({
"unique_ids":
tf.constant(all_unique_ids, shape=[num_examples], dtype=tf.int32),
"input_ids":
tf.constant(
all_input_ids, shape=[num_examples, seq_length],
dtype=tf.int32),
"input_mask":
tf.constant(
all_input_mask,
shape=[num_examples, seq_length],
dtype=tf.int32),
"input_type_ids":
tf.constant(
all_input_type_ids,
shape=[num_examples, seq_length],
dtype=tf.int32),
})
d = d.batch(batch_size=batch_size, drop_remainder=False)
return d
return input_fn
def model_fn_builder(bert_config, init_checkpoint, layer_indexes, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
unique_ids = features["unique_ids"]
input_ids = features["input_ids"]
input_mask = features["input_mask"]
input_type_ids = features["input_type_ids"]
model = modeling.BertModel(
config=bert_config,
is_training=False,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=input_type_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
if mode != tf.estimator.ModeKeys.PREDICT:
raise ValueError("Only PREDICT modes are supported: %s" % (mode))
tvars = tf.trainable_variables()
scaffold_fn = None
(assignment_map,
initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(
tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
all_layers = model.get_all_encoder_layers()
predictions = {
"unique_id": unique_ids,
}
for (i, layer_index) in enumerate(layer_indexes):
predictions["layer_output_%d" % i] = all_layers[layer_index]
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
return output_spec
return model_fn
def convert_examples_to_features(examples, seq_length, tokenizer):
"""Loads a data file into a list of `InputBatch`s."""
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
if tokens_b:
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for [CLS], [SEP], [SEP] with "- 3"
_truncate_seq_pair(tokens_a, tokens_b, seq_length - 3)
else:
# Account for [CLS] and [SEP] with "- 2"
if len(tokens_a) > seq_length - 2:
tokens_a = tokens_a[0:(seq_length - 2)]
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens = []
input_type_ids = []
tokens.append("[CLS]")
input_type_ids.append(0)
for token in tokens_a:
tokens.append(token)
input_type_ids.append(0)
tokens.append("[SEP]")
input_type_ids.append(0)
if tokens_b:
for token in tokens_b:
tokens.append(token)
input_type_ids.append(1)
tokens.append("[SEP]")
input_type_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < seq_length:
input_ids.append(0)
input_mask.append(0)
input_type_ids.append(0)
assert len(input_ids) == seq_length
assert len(input_mask) == seq_length
assert len(input_type_ids) == seq_length
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("unique_id: %s" % (example.unique_id))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info(
"input_type_ids: %s" % " ".join([str(x) for x in input_type_ids]))
features.append(
InputFeatures(
unique_id=example.unique_id,
tokens=tokens,
input_ids=input_ids,
input_mask=input_mask,
input_type_ids=input_type_ids))
return features
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def read_examples(input_file):
"""Read a list of `InputExample`s from an input file."""
examples = []
unique_id = 0
with tf.gfile.GFile(input_file, "r") as reader:
while True:
line = tokenization.convert_to_unicode(reader.readline())
if not line:
break
line = line.strip()
text_a = None
text_b = None
m = re.match(r"^(.*) \|\|\| (.*)$", line)
if m is None:
text_a = line
else:
text_a = m.group(1)
text_b = m.group(2)
examples.append(
InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b))
unique_id += 1
return examples
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
layer_indexes = [int(x) for x in FLAGS.layers.split(",")]
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
master=FLAGS.master,
tpu_config=tf.contrib.tpu.TPUConfig(
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
examples = read_examples(FLAGS.input_file)
features = convert_examples_to_features(
examples=examples, seq_length=FLAGS.max_seq_length, tokenizer=tokenizer)
unique_id_to_feature = {}
for feature in features:
unique_id_to_feature[feature.unique_id] = feature
model_fn = model_fn_builder(
bert_config=bert_config,
init_checkpoint=FLAGS.init_checkpoint,
layer_indexes=layer_indexes,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_one_hot_embeddings)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
predict_batch_size=FLAGS.batch_size)
input_fn = input_fn_builder(
features=features, seq_length=FLAGS.max_seq_length)
with codecs.getwriter("utf-8")(tf.gfile.Open(FLAGS.output_file,
"w")) as writer:
for result in estimator.predict(input_fn, yield_single_examples=True):
unique_id = int(result["unique_id"])
feature = unique_id_to_feature[unique_id]
output_json = collections.OrderedDict()
output_json["linex_index"] = unique_id
all_features = []
for (i, token) in enumerate(feature.tokens):
all_layers = []
for (j, layer_index) in enumerate(layer_indexes):
layer_output = result["layer_output_%d" % j]
layers = collections.OrderedDict()
layers["index"] = layer_index
layers["values"] = [
round(float(x), 6) for x in layer_output[i:(i + 1)].flat
]
all_layers.append(layers)
features = collections.OrderedDict()
features["token"] = token
features["layers"] = all_layers
all_features.append(features)
output_json["features"] = all_features
writer.write(json.dumps(output_json) + "\n")
if __name__ == "__main__":
flags.mark_flag_as_required("input_file")
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("init_checkpoint")
flags.mark_flag_as_required("output_file")
tf.app.run()
| 13,898 | 32.092857 | 82 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/modeling_test.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import json
import random
import re
import modeling
import six
import tensorflow as tf
class BertModelTest(tf.test.TestCase):
class BertModelTester(object):
def __init__(self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
vocab_size=99,
hidden_size=32,
num_hidden_layers=5,
num_attention_heads=4,
intermediate_size=37,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=16,
initializer_range=0.02,
scope=None):
self.parent = parent
self.batch_size = batch_size
self.seq_length = seq_length
self.is_training = is_training
self.use_input_mask = use_input_mask
self.use_token_type_ids = use_token_type_ids
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
self.scope = scope
def create_model(self):
input_ids = BertModelTest.ids_tensor([self.batch_size, self.seq_length],
self.vocab_size)
input_mask = None
if self.use_input_mask:
input_mask = BertModelTest.ids_tensor(
[self.batch_size, self.seq_length], vocab_size=2)
token_type_ids = None
if self.use_token_type_ids:
token_type_ids = BertModelTest.ids_tensor(
[self.batch_size, self.seq_length], self.type_vocab_size)
config = modeling.BertConfig(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
max_position_embeddings=self.max_position_embeddings,
type_vocab_size=self.type_vocab_size,
initializer_range=self.initializer_range)
model = modeling.BertModel(
config=config,
is_training=self.is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=token_type_ids,
scope=self.scope)
outputs = {
"embedding_output": model.get_embedding_output(),
"sequence_output": model.get_sequence_output(),
"pooled_output": model.get_pooled_output(),
"all_encoder_layers": model.get_all_encoder_layers(),
}
return outputs
def check_output(self, result):
self.parent.assertAllEqual(
result["embedding_output"].shape,
[self.batch_size, self.seq_length, self.hidden_size])
self.parent.assertAllEqual(
result["sequence_output"].shape,
[self.batch_size, self.seq_length, self.hidden_size])
self.parent.assertAllEqual(result["pooled_output"].shape,
[self.batch_size, self.hidden_size])
def test_default(self):
self.run_tester(BertModelTest.BertModelTester(self))
def test_config_to_json_string(self):
config = modeling.BertConfig(vocab_size=99, hidden_size=37)
obj = json.loads(config.to_json_string())
self.assertEqual(obj["vocab_size"], 99)
self.assertEqual(obj["hidden_size"], 37)
def run_tester(self, tester):
with self.test_session() as sess:
ops = tester.create_model()
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess.run(init_op)
output_result = sess.run(ops)
tester.check_output(output_result)
self.assert_all_tensors_reachable(sess, [init_op, ops])
@classmethod
def ids_tensor(cls, shape, vocab_size, rng=None, name=None):
"""Creates a random int32 tensor of the shape within the vocab size."""
if rng is None:
rng = random.Random()
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append(rng.randint(0, vocab_size - 1))
return tf.constant(value=values, dtype=tf.int32, shape=shape, name=name)
def assert_all_tensors_reachable(self, sess, outputs):
"""Checks that all the tensors in the graph are reachable from outputs."""
graph = sess.graph
ignore_strings = [
"^.*/assert_less_equal/.*$",
"^.*/dilation_rate$",
"^.*/Tensordot/concat$",
"^.*/Tensordot/concat/axis$",
"^testing/.*$",
]
ignore_regexes = [re.compile(x) for x in ignore_strings]
unreachable = self.get_unreachable_ops(graph, outputs)
filtered_unreachable = []
for x in unreachable:
do_ignore = False
for r in ignore_regexes:
m = r.match(x.name)
if m is not None:
do_ignore = True
if do_ignore:
continue
filtered_unreachable.append(x)
unreachable = filtered_unreachable
self.assertEqual(
len(unreachable), 0, "The following ops are unreachable: %s" %
(" ".join([x.name for x in unreachable])))
@classmethod
def get_unreachable_ops(cls, graph, outputs):
"""Finds all of the tensors in graph that are unreachable from outputs."""
outputs = cls.flatten_recursive(outputs)
output_to_op = collections.defaultdict(list)
op_to_all = collections.defaultdict(list)
assign_out_to_in = collections.defaultdict(list)
for op in graph.get_operations():
for x in op.inputs:
op_to_all[op.name].append(x.name)
for y in op.outputs:
output_to_op[y.name].append(op.name)
op_to_all[op.name].append(y.name)
if str(op.type) == "Assign":
for y in op.outputs:
for x in op.inputs:
assign_out_to_in[y.name].append(x.name)
assign_groups = collections.defaultdict(list)
for out_name in assign_out_to_in.keys():
name_group = assign_out_to_in[out_name]
for n1 in name_group:
assign_groups[n1].append(out_name)
for n2 in name_group:
if n1 != n2:
assign_groups[n1].append(n2)
seen_tensors = {}
stack = [x.name for x in outputs]
while stack:
name = stack.pop()
if name in seen_tensors:
continue
seen_tensors[name] = True
if name in output_to_op:
for op_name in output_to_op[name]:
if op_name in op_to_all:
for input_name in op_to_all[op_name]:
if input_name not in stack:
stack.append(input_name)
expanded_names = []
if name in assign_groups:
for assign_name in assign_groups[name]:
expanded_names.append(assign_name)
for expanded_name in expanded_names:
if expanded_name not in stack:
stack.append(expanded_name)
unreachable_ops = []
for op in graph.get_operations():
is_unreachable = False
all_names = [x.name for x in op.inputs] + [x.name for x in op.outputs]
for name in all_names:
if name not in seen_tensors:
is_unreachable = True
if is_unreachable:
unreachable_ops.append(op)
return unreachable_ops
@classmethod
def flatten_recursive(cls, item):
"""Flattens (potentially nested) a tuple/dictionary/list to a list."""
output = []
if isinstance(item, list):
output.extend(item)
elif isinstance(item, tuple):
output.extend(list(item))
elif isinstance(item, dict):
for (_, v) in six.iteritems(item):
output.append(v)
else:
return [item]
flat_output = []
for x in output:
flat_output.extend(cls.flatten_recursive(x))
return flat_output
if __name__ == "__main__":
tf.test.main()
| 9,191 | 32.064748 | 78 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/conlleval.py | # Python version of the evaluation script from CoNLL'00-
# Originates from: https://github.com/spyysalo/conlleval.py
# Intentional differences:
# - accept any space as delimiter by default
# - optional file argument (default STDIN)
# - option to set boundary (-b argument)
# - LaTeX output (-l argument) not supported
# - raw tags (-r argument) not supported
# add function :evaluate(predicted_label, ori_label): which will not read from file
import sys
import re
import codecs
from collections import defaultdict, namedtuple
ANY_SPACE = '<SPACE>'
class FormatError(Exception):
pass
Metrics = namedtuple('Metrics', 'tp fp fn prec rec fscore')
class EvalCounts(object):
def __init__(self):
self.correct_chunk = 0 # number of correctly identified chunks
self.correct_tags = 0 # number of correct chunk tags
self.found_correct = 0 # number of chunks in corpus
self.found_guessed = 0 # number of identified chunks
self.token_counter = 0 # token counter (ignores sentence breaks)
# counts by type
self.t_correct_chunk = defaultdict(int)
self.t_found_correct = defaultdict(int)
self.t_found_guessed = defaultdict(int)
def parse_args(argv):
import argparse
parser = argparse.ArgumentParser(
description='evaluate tagging results using CoNLL criteria',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
arg = parser.add_argument
arg('-b', '--boundary', metavar='STR', default='-X-',
help='sentence boundary')
arg('-d', '--delimiter', metavar='CHAR', default=ANY_SPACE,
help='character delimiting items in input')
arg('-o', '--otag', metavar='CHAR', default='O',
help='alternative outside tag')
arg('file', nargs='?', default=None)
return parser.parse_args(argv)
def parse_tag(t):
m = re.match(r'^([^-]*)-(.*)$', t)
return m.groups() if m else (t, '')
def evaluate(iterable, options=None):
if options is None:
options = parse_args([]) # use defaults
counts = EvalCounts()
num_features = None # number of features per line
in_correct = False # currently processed chunks is correct until now
last_correct = 'O' # previous chunk tag in corpus
last_correct_type = '' # type of previously identified chunk tag
last_guessed = 'O' # previously identified chunk tag
last_guessed_type = '' # type of previous chunk tag in corpus
for line in iterable:
line = line.rstrip('\r\n')
if options.delimiter == ANY_SPACE:
features = line.split()
else:
features = line.split(options.delimiter)
if num_features is None:
num_features = len(features)
elif num_features != len(features) and len(features) != 0:
raise FormatError('unexpected number of features: %d (%d)' %
(len(features), num_features))
if len(features) == 0 or features[0] == options.boundary:
features = [options.boundary, 'O', 'O']
if len(features) < 3:
raise FormatError('unexpected number of features in line %s' % line)
guessed, guessed_type = parse_tag(features.pop())
correct, correct_type = parse_tag(features.pop())
first_item = features.pop(0)
if first_item == options.boundary:
guessed = 'O'
end_correct = end_of_chunk(last_correct, correct,
last_correct_type, correct_type)
end_guessed = end_of_chunk(last_guessed, guessed,
last_guessed_type, guessed_type)
start_correct = start_of_chunk(last_correct, correct,
last_correct_type, correct_type)
start_guessed = start_of_chunk(last_guessed, guessed,
last_guessed_type, guessed_type)
if in_correct:
if (end_correct and end_guessed and
last_guessed_type == last_correct_type):
in_correct = False
counts.correct_chunk += 1
counts.t_correct_chunk[last_correct_type] += 1
elif (end_correct != end_guessed or guessed_type != correct_type):
in_correct = False
if start_correct and start_guessed and guessed_type == correct_type:
in_correct = True
if start_correct:
counts.found_correct += 1
counts.t_found_correct[correct_type] += 1
if start_guessed:
counts.found_guessed += 1
counts.t_found_guessed[guessed_type] += 1
if first_item != options.boundary:
if correct == guessed and guessed_type == correct_type:
counts.correct_tags += 1
counts.token_counter += 1
last_guessed = guessed
last_correct = correct
last_guessed_type = guessed_type
last_correct_type = correct_type
if in_correct:
counts.correct_chunk += 1
counts.t_correct_chunk[last_correct_type] += 1
return counts
def uniq(iterable):
seen = set()
return [i for i in iterable if not (i in seen or seen.add(i))]
def calculate_metrics(correct, guessed, total):
tp, fp, fn = correct, guessed-correct, total-correct
p = 0 if tp + fp == 0 else 1.*tp / (tp + fp)
r = 0 if tp + fn == 0 else 1.*tp / (tp + fn)
f = 0 if p + r == 0 else 2 * p * r / (p + r)
return Metrics(tp, fp, fn, p, r, f)
def metrics(counts):
c = counts
overall = calculate_metrics(
c.correct_chunk, c.found_guessed, c.found_correct
)
by_type = {}
for t in uniq(list(c.t_found_correct) + list(c.t_found_guessed)):
by_type[t] = calculate_metrics(
c.t_correct_chunk[t], c.t_found_guessed[t], c.t_found_correct[t]
)
return overall, by_type
def report(counts, out=None):
if out is None:
out = sys.stdout
overall, by_type = metrics(counts)
c = counts
out.write('processed %d tokens with %d phrases; ' %
(c.token_counter, c.found_correct))
out.write('found: %d phrases; correct: %d.\n' %
(c.found_guessed, c.correct_chunk))
if c.token_counter > 0:
out.write('accuracy: %6.2f%%; ' %
(100.*c.correct_tags/c.token_counter))
out.write('precision: %6.2f%%; ' % (100.*overall.prec))
out.write('recall: %6.2f%%; ' % (100.*overall.rec))
out.write('FB1: %6.2f\n' % (100.*overall.fscore))
for i, m in sorted(by_type.items()):
out.write('%17s: ' % i)
out.write('precision: %6.2f%%; ' % (100.*m.prec))
out.write('recall: %6.2f%%; ' % (100.*m.rec))
out.write('FB1: %6.2f %d\n' % (100.*m.fscore, c.t_found_guessed[i]))
def report_notprint(counts, out=None):
if out is None:
out = sys.stdout
overall, by_type = metrics(counts)
c = counts
final_report = []
line = []
line.append('processed %d tokens with %d phrases; ' %
(c.token_counter, c.found_correct))
line.append('found: %d phrases; correct: %d.\n' %
(c.found_guessed, c.correct_chunk))
final_report.append("".join(line))
if c.token_counter > 0:
line = []
line.append('accuracy: %6.2f%%; ' %
(100.*c.correct_tags/c.token_counter))
line.append('precision: %6.2f%%; ' % (100.*overall.prec))
line.append('recall: %6.2f%%; ' % (100.*overall.rec))
line.append('FB1: %6.2f\n' % (100.*overall.fscore))
final_report.append("".join(line))
for i, m in sorted(by_type.items()):
line = []
line.append('%17s: ' % i)
line.append('precision: %6.2f%%; ' % (100.*m.prec))
line.append('recall: %6.2f%%; ' % (100.*m.rec))
line.append('FB1: %6.2f %d\n' % (100.*m.fscore, c.t_found_guessed[i]))
final_report.append("".join(line))
return final_report
def end_of_chunk(prev_tag, tag, prev_type, type_):
# check if a chunk ended between the previous and current word
# arguments: previous and current chunk tags, previous and current types
chunk_end = False
if prev_tag == 'E': chunk_end = True
if prev_tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'B': chunk_end = True
if prev_tag == 'B' and tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'O': chunk_end = True
if prev_tag == 'I' and tag == 'B': chunk_end = True
if prev_tag == 'I' and tag == 'S': chunk_end = True
if prev_tag == 'I' and tag == 'O': chunk_end = True
if prev_tag != 'O' and prev_tag != '.' and prev_type != type_:
chunk_end = True
# these chunks are assumed to have length 1
if prev_tag == ']': chunk_end = True
if prev_tag == '[': chunk_end = True
return chunk_end
def start_of_chunk(prev_tag, tag, prev_type, type_):
# check if a chunk started between the previous and current word
# arguments: previous and current chunk tags, previous and current types
chunk_start = False
if tag == 'B': chunk_start = True
if tag == 'S': chunk_start = True
if prev_tag == 'E' and tag == 'E': chunk_start = True
if prev_tag == 'E' and tag == 'I': chunk_start = True
if prev_tag == 'S' and tag == 'E': chunk_start = True
if prev_tag == 'S' and tag == 'I': chunk_start = True
if prev_tag == 'O' and tag == 'E': chunk_start = True
if prev_tag == 'O' and tag == 'I': chunk_start = True
if tag != 'O' and tag != '.' and prev_type != type_:
chunk_start = True
# these chunks are assumed to have length 1
if tag == '[': chunk_start = True
if tag == ']': chunk_start = True
return chunk_start
def return_report(input_file):
with codecs.open(input_file, "r", "utf8") as f:
counts = evaluate(f)
return report_notprint(counts)
def main(argv):
args = parse_args(argv[1:])
if args.file is None:
counts = evaluate(sys.stdin, args)
else:
with open(args.file) as f:
counts = evaluate(f, args)
report(counts)
if __name__ == '__main__':
sys.exit(main(sys.argv)) | 10,196 | 32.99 | 83 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/optimization_test.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import optimization
import tensorflow as tf
class OptimizationTest(tf.test.TestCase):
def test_adam(self):
with self.test_session() as sess:
w = tf.get_variable(
"w",
shape=[3],
initializer=tf.constant_initializer([0.1, -0.2, -0.1]))
x = tf.constant([0.4, 0.2, -0.5])
loss = tf.reduce_mean(tf.square(x - w))
tvars = tf.trainable_variables()
grads = tf.gradients(loss, tvars)
global_step = tf.train.get_or_create_global_step()
optimizer = optimization.AdamWeightDecayOptimizer(learning_rate=0.2)
train_op = optimizer.apply_gradients(zip(grads, tvars), global_step)
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess.run(init_op)
for _ in range(100):
sess.run(train_op)
w_np = sess.run(w)
self.assertAllClose(w_np.flat, [0.4, 0.2, -0.5], rtol=1e-2, atol=1e-2)
if __name__ == "__main__":
tf.test.main()
| 1,721 | 34.142857 | 76 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/run_ner.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BERT finetuning runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
import modeling
import optimization
import tokenization
import tensorflow as tf
from sklearn.metrics import f1_score, precision_score, recall_score
from tensorflow.python.ops import math_ops
import tf_metrics
import pickle
import codecs
import sys
import sys
reload(sys)
sys.setdefaultencoding('utf8')
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_string(
"data_dir", None,
"The input datadir.",
)
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model."
)
flags.DEFINE_string(
"task_name", None, "The name of the task to train."
)
flags.DEFINE_string(
"token_name", "full", "The name of the task to train."
)
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written."
)
## Other parameters
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model)."
)
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text."
)
flags.DEFINE_integer(
"max_seq_length", 128,
"The maximum total input sequence length after WordPiece tokenization."
)
flags.DEFINE_bool(
"do_train", False,
"Whether to run training."
)
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
flags.DEFINE_bool("do_predict", False, "Whether to run the model in inference mode on the test set.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predict.")
flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
flags.DEFINE_float("num_train_epochs", 3.0, "Total number of training epochs to perform.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text, label=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text = text
self.label = label
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, input_ids, input_mask, segment_ids, label_ids, label_mask):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_ids = label_ids
self.label_mask = label_mask
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
@classmethod
def _read_data(cls, input_file):
"""Reads a BIO data."""
with open(input_file) as f:
lines = []
words = []
labels = []
for line in f:
contends = line.strip()
word = line.strip().split(' ')[0]
label = line.strip().split(' ')[-1]
if contends.startswith("-DOCSTART-"):
words.append('')
continue
if len(contends) == 0 and words[-1] == '.':
l = ' '.join([label for label in labels if len(label) > 0])
w = ' '.join([word for word in words if len(word) > 0])
lines.append([l, w])
words = []
labels = []
continue
if len(contends) == 0:
continue
words.append(word)
labels.append(label)
return lines
class NerProcessor(DataProcessor):
def get_train_examples(self, data_dir):
return self._create_example(
self._read_data(os.path.join(data_dir, "train.txt")), "train"
)
def get_dev_examples(self, data_dir):
return self._create_example(
self._read_data(os.path.join(data_dir, "dev.txt")), "dev"
)
def get_test_examples(self, data_dir):
return self._create_example(
self._read_data(os.path.join(data_dir, "test.txt")), "test")
def get_labels(self):
# return ["I-MISC", "I-PER", "I-ORG", "I-LOC", "O", "X", "[CLS]", "[SEP]"]
return ["B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", "O", "X", "[CLS]", "[SEP]"]
def _create_example(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text = tokenization.convert_to_unicode(line[1])
label = tokenization.convert_to_unicode(line[0])
examples.append(InputExample(guid=guid, text=text, label=label))
return examples
class WeiboNERProcessor(DataProcessor):
def __init_(self):
self.labels = set()
def get_train_examples(self, data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "weiboNER.conll.train")), "train"
)
def get_dev_examples(self, data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "weiboNER.conll.dev")), "dev"
)
def get_test_examples(self,data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "weiboNER.conll.test")), "test")
def get_labels(self):
return ['I-PER.NOM', 'I-PER.NAM', 'I-GPE.NAM', 'I-ORG.NAM', 'I-ORG.NOM', 'I-LOC.NAM', 'I-LOC.NOM', "O", "X", "[CLS]", "[SEP]"]
# return ['B-PER.NOM', 'I-PER.NOM', 'B-LOC.NAM', 'B-PER.NAM', 'I-PER.NAM', 'B-GPE.NAM', 'I-GPE.NAM', 'B-ORG.NAM', 'I-ORG.NAM', 'B-ORG.NOM', 'I-ORG.NOM', 'I-LOC.NAM', 'B-LOC.NOM', 'I-LOC.NOM', "O", "X", "[CLS]", "[SEP]"]
def _create_example(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text = tokenization.convert_to_unicode(line[1])
label = tokenization.convert_to_unicode(line[0])
examples.append(InputExample(guid=guid, text=text, label=label))
return examples
def _read_raw(self, input_file):
with codecs.open(input_file, 'r', encoding='utf-8') as f:
lines = []
words = []
labels = []
for line in f:
contends = line.strip()
tokens = contends.split()
if len(tokens) == 2:
words.append(tokens[0])
label = tokens[-1]
if label[0] == 'B':
label = "I" + label[1:]
labels.append(label)
else:
if len(contends) == 0 and len(words) > 0:
label = []
word = []
for l, w in zip(labels, words):
if len(l) > 0 and len(w) > 0:
label.append(l)
# self.labels.add(l)
word.append(w)
lines.append([' '.join(label), ' '.join(word)])
words = []
labels = []
continue
if contends.startswith("-DOCSTART-"):
continue
return lines
class MsraNERProcessor(DataProcessor):
def __init_(self):
self.labels = set()
def get_train_examples(self, data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "train1.txt")), "train"
)
def get_dev_examples(self, data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "testright1.txt")), "dev"
)
def get_test_examples(self,data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "testright1.txt")), "test")
def get_labels(self):
return ['B-PERSON', 'I-PERSON', 'B-LOCATION', 'I-LOCATION', 'B-ORGANIZATION', 'I-ORGANIZATION', "O", "[CLS]", "[SEP]", "X"]
def _create_example(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text = tokenization.convert_to_unicode(line[1])
label = tokenization.convert_to_unicode(line[0])
examples.append(InputExample(guid=guid, text=text, label=label))
return examples
def _read_raw(self, input_file):
with codecs.open(input_file, 'r', encoding='utf-8') as f:
lines = []
chars = []
labels = []
len_count = []
for line in f:
contends = line.strip()
tokens = contends.split()
for token in tokens:
word, label = token.split('/')
if label == "nr":
chars = chars + list(word)
labels = labels + ['B-PERSON'] + ['I-PERSON']*(len(word)-1)
elif label == "ns":
chars = chars + list(word)
labels = labels + ['B-LOCATION'] + ['I-LOCATION']*(len(word)-1)
elif label == "nt":
chars = chars + list(word)
labels = labels + ['B-ORGANIZATION'] + ['I-ORGANIZATION']*(len(word)-1)
else:
assert label == "o"
chars = chars + list(word)
labels = labels + ["O"] * len(word)
lines.append([' '.join(labels), ' '.join(chars)])
len_count.append(len(chars))
chars = []
labels = []
return lines
def write_tokens(tokens, mode):
if mode == "test":
path = os.path.join(FLAGS.output_dir, "token_" + mode + ".txt")
wf = open(path, 'a')
for token in tokens:
if token != "**NULL**":
wf.write(token + '\n')
wf.close()
def convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer, output_dir, mode):
label_map = {}
for (i, label) in enumerate(label_list, 1):
label_map[label] = i
if not os.path.exists(os.path.join(output_dir, 'label2id.pkl')):
with open(os.path.join(output_dir, 'label2id.pkl'), 'wb') as w:
pickle.dump(label_map, w)
textlist = example.text.split(' ')
labellist = example.label.split(' ')
tokens = []
labels = []
label_mask = []
for i, word in enumerate(textlist):
token = tokenizer.tokenize(word)
tokens.extend(token)
label_1 = labellist[i]
for m in range(len(token)):
if m == 0:
labels.append(label_1)
else:
labels.append("X")
# tokens = tokenizer.tokenize(example.text)
if len(tokens) >= max_seq_length - 1:
tokens = tokens[0:(max_seq_length - 2)]
labels = labels[0:(max_seq_length - 2)]
ntokens = []
segment_ids = []
label_ids = []
ntokens.append("[CLS]")
segment_ids.append(0)
# append("O") or append("[CLS]") not sure!
label_ids.append(label_map["[CLS]"])
label_mask.append(0) # not to predict and train
for i, token in enumerate(tokens):
ntokens.append(token)
segment_ids.append(0)
label_ids.append(label_map[labels[i]])
if labels[i] == 'X':
label_mask.append(0)
else:
label_mask.append(1)
ntokens.append("[SEP]")
segment_ids.append(0)
label_mask.append(0)
# append("O") or append("[SEP]") not sure!
label_ids.append(label_map["[SEP]"])
input_ids = tokenizer.convert_tokens_to_ids(ntokens)
input_mask = [1] * len(input_ids)
# label_mask = [1] * len(input_ids)
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
# we don't concerned about it!
label_ids.append(0)
ntokens.append("**NULL**")
label_mask.append(0)
# print(len(input_ids))
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
assert len(label_ids) == max_seq_length
assert len(label_mask) == max_seq_length
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label_ids: %s" % " ".join([str(x) for x in label_ids]))
tf.logging.info("label_mask: %s" % " ".join([str(x) for x in label_mask]))
# tf.logging.info("label_mask: %s" % " ".join([str(x) for x in label_mask]))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_ids=label_ids,
label_mask = label_mask
)
write_tokens(ntokens, mode)
return feature
def file_based_convert_examples_to_features(
examples, label_list, max_seq_length, tokenizer, output_file, output_dir, mode=None
):
writer = tf.python_io.TFRecordWriter(output_file)
for (ex_index, example) in enumerate(examples):
if ex_index % 5000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer, output_dir, mode)
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
features = collections.OrderedDict()
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["label_ids"] = create_int_feature(feature.label_ids)
features["label_mask"] = create_int_feature(feature.label_mask)
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder):
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_mask": tf.FixedLenFeature([seq_length], tf.int64),
}
def _decode_record(record, name_to_features):
example = tf.parse_single_example(record, name_to_features)
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
batch_size = params["batch_size"]
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.apply(tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder
))
return d
return input_fn
def create_model(bert_config, is_training, input_ids, input_mask, label_mask,
segment_ids, labels, num_labels, use_one_hot_embeddings):
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings
)
output_layer = model.get_sequence_output()
hidden_size = output_layer.shape[-1].value
output_weight = tf.get_variable(
"output_weights", [num_labels, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02)
)
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer()
)
with tf.variable_scope("loss"):
if is_training:
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
output_layer = tf.reshape(output_layer, [-1, hidden_size])
logits = tf.matmul(output_layer, output_weight, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
logits = tf.reshape(logits, [-1, FLAGS.max_seq_length, num_labels])
# mask = tf.cast(input_mask,tf.float32)
# loss = tf.contrib.seq2seq.sequence_loss(logits,labels,mask)
# return (loss, logits, predict)
##########################################################################
log_probs = tf.nn.log_softmax(logits, axis=-1)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
mask = tf.cast(label_mask, tf.float32)
mask_example_loss = per_example_loss * mask
loss = tf.reduce_sum(mask_example_loss)
probabilities = tf.nn.softmax(logits, axis=-1)
predict = tf.argmax(probabilities, axis=-1)
return (loss, mask_example_loss, logits, predict)
##########################################################################
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
def model_fn(features, labels, mode, params):
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]
label_mask = features["label_mask"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(total_loss, per_example_loss, logits, predicts) = create_model(
bert_config, is_training, input_ids, input_mask, label_mask, segment_ids, label_ids,
num_labels, use_one_hot_embeddings)
tvars = tf.trainable_variables()
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars,
init_checkpoint)
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
hook_dict = {}
hook_dict['loss'] = total_loss
hook_dict['global_steps'] = tf.train.get_or_create_global_step()
logging_hook = tf.train.LoggingTensorHook(
hook_dict, every_n_iter=200)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn,
training_hooks=[logging_hook])
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits):
# def metric_fn(label_ids, logits):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
# labels = []
# for i, x in enumerate()
predict_labels = []
# for i in range(1, num_labels - 4):
# predict_labels.append(i)
# precision = tf_metrics.precision(label_ids, predictions, num_labels, predict_labels, average="macro")
# recall = tf_metrics.recall(label_ids, predictions, num_labels, predict_labels, average="macro")
# f = tf_metrics.f1(label_ids, predictions, num_labels, predict_labels, average="macro")
precision = tf_metrics.precision(label_ids, predictions, num_labels, average="macro")
recall = tf_metrics.recall(label_ids, predictions, num_labels, average="macro")
f = tf_metrics.f1(label_ids, predictions, num_labels, average="macro")
#
return {
"eval_precision": precision,
"eval_recall": recall,
"eval_f": f,
# "eval_loss": loss,
}
eval_metrics = (metric_fn, [per_example_loss, label_ids, logits])
# eval_metrics = (metric_fn, [label_ids, logits])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions=predicts, scaffold_fn=scaffold_fn
)
return output_spec
return model_fn
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"ner": NerProcessor,
"weiboner": WeiboNERProcessor,
"msraner": MsraNERProcessor
}
# if not FLAGS.do_train and not FLAGS.do_eval:
# raise ValueError("At least one of `do_train` or `do_eval` must be True.")
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
if FLAGS.max_seq_length > bert_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, bert_config.max_position_embeddings))
if not os.path.exists(FLAGS.output_dir):
os.mkdir(FLAGS.output_dir)
task_name = FLAGS.task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
label_list = processor.get_labels()
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = processor.get_train_examples(FLAGS.data_dir)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
print(num_train_steps)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
model_fn = model_fn_builder(
bert_config=bert_config,
num_labels=len(label_list) + 1,
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file, FLAGS.output_dir)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = file_based_input_fn_builder(
input_file=train_file,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_eval:
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")
file_based_convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file, FLAGS.output_dir)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d", len(eval_examples))
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
eval_steps = None
if FLAGS.use_tpu:
eval_steps = int(len(eval_examples) / FLAGS.eval_batch_size)
eval_drop_remainder = True if FLAGS.use_tpu else False
eval_input_fn = file_based_input_fn_builder(
input_file=eval_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=eval_drop_remainder)
result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with open(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_predict:
pred_tags = []
true_tags = []
token_path = os.path.join(FLAGS.output_dir, "token_test.txt")
label_file = os.path.join(FLAGS.output_dir, "label2id.pkl")
label_masks = []
with open(label_file, "rb") as rf:
label2id = pickle.load(rf)
id2label = {value: key for key, value in label2id.items()}
if os.path.exists(token_path):
os.remove(token_path)
predict_examples = processor.get_test_examples(FLAGS.data_dir)
ground_truth_file = os.path.join(FLAGS.output_dir, "ground_truth.txt")
with open(ground_truth_file, 'w') as writer:
for ex_index, example in enumerate(predict_examples):
feature = convert_single_example(ex_index, example, label_list, FLAGS.max_seq_length, tokenizer, FLAGS.output_dir, "test")
line = []
for i, id in enumerate(feature.label_ids):
if feature.label_mask[i] == 1:
line.append(id2label[id])
true_tags.append(id2label[id])
# output_line = " ".join(id2label[id] for id in feature.label_ids if id != 0) + "\n"
output_line = " ".join(line) + "\n"
writer.write(output_line)
label_masks.append(feature.label_mask)
predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
file_based_convert_examples_to_features(predict_examples, label_list,
FLAGS.max_seq_length, tokenizer,
predict_file, FLAGS.output_dir, mode="test")
tf.logging.info("***** Running prediction*****")
tf.logging.info(" Num examples = %d", len(predict_examples))
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
if FLAGS.use_tpu:
# Warning: According to tpu_estimator.py Prediction on TPU is an
# experimental feature and hence not supported here
raise ValueError("Prediction in TPU not supported")
predict_drop_remainder = True if FLAGS.use_tpu else False
predict_input_fn = file_based_input_fn_builder(
input_file=predict_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=predict_drop_remainder)
result = estimator.predict(input_fn=predict_input_fn)
output_predict_file = os.path.join(FLAGS.output_dir, "label_test.txt")
with open(output_predict_file, 'w') as writer:
for i, prediction in enumerate(result):
line = []
for j, x in enumerate(prediction):
if label_masks[i][j] == 0:
continue
else:
line.append(id2label[x])
# writer.write(id2label[x] + "\n")
pred_tags.append(id2label[x])
output_line = " ".join(line) + "\n"
# # output_line = " ".join(id2label[id] for id in prediction if id != 0) + "\n"
writer.write(output_line)
# evaluate(true_tags, pred_tags, verbose=True)
# evaluate(true_tags, pred_tags)
tmp = codecs.open(os.path.join(FLAGS.output_dir, "tmp"), 'w', 'utf8')
with codecs.open(ground_truth_file, 'r', 'utf8') as ft, codecs.open(output_predict_file, 'r', 'utf8') as fg:
for lt, lg in zip(ft, fg):
for tl, tg in zip(lt.strip().split(), lg.strip().split()):
print('\t'.join([" ", tl, tg]), file=tmp)
tmp.close()
cmd = "python %s -d '\t' < %s > %s" % \
(os.path.join(os.getcwd(), "conlleval.py"), \
os.path.join(FLAGS.output_dir, "tmp"), \
os.path.join(FLAGS.data_dir, "test_results_roberta_wwm_ext.txt"))
os.system(cmd)
if __name__ == "__main__":
flags.mark_flag_as_required("data_dir")
flags.mark_flag_as_required("task_name")
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| 33,814 | 39.017751 | 227 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/tokenization_test.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
import tokenization
import six
import tensorflow as tf
class TokenizationTest(tf.test.TestCase):
def test_full_tokenizer(self):
vocab_tokens = [
"[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
"##ing", ","
]
with tempfile.NamedTemporaryFile(delete=False) as vocab_writer:
if six.PY2:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
else:
vocab_writer.write("".join(
[x + "\n" for x in vocab_tokens]).encode("utf-8"))
vocab_file = vocab_writer.name
tokenizer = tokenization.FullTokenizer(vocab_file)
os.unlink(vocab_file)
tokens = tokenizer.tokenize(u"UNwant\u00E9d,running")
self.assertAllEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"])
self.assertAllEqual(
tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9])
def test_chinese(self):
tokenizer = tokenization.BasicTokenizer()
self.assertAllEqual(
tokenizer.tokenize(u"ah\u535A\u63A8zz"),
[u"ah", u"\u535A", u"\u63A8", u"zz"])
def test_basic_tokenizer_lower(self):
tokenizer = tokenization.BasicTokenizer(do_lower_case=True)
self.assertAllEqual(
tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "),
["hello", "!", "how", "are", "you", "?"])
self.assertAllEqual(tokenizer.tokenize(u"H\u00E9llo"), ["hello"])
def test_basic_tokenizer_no_lower(self):
tokenizer = tokenization.BasicTokenizer(do_lower_case=False)
self.assertAllEqual(
tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "),
["HeLLo", "!", "how", "Are", "yoU", "?"])
def test_wordpiece_tokenizer(self):
vocab_tokens = [
"[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
"##ing"
]
vocab = {}
for (i, token) in enumerate(vocab_tokens):
vocab[token] = i
tokenizer = tokenization.WordpieceTokenizer(vocab=vocab)
self.assertAllEqual(tokenizer.tokenize(""), [])
self.assertAllEqual(
tokenizer.tokenize("unwanted running"),
["un", "##want", "##ed", "runn", "##ing"])
self.assertAllEqual(
tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"])
def test_convert_tokens_to_ids(self):
vocab_tokens = [
"[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
"##ing"
]
vocab = {}
for (i, token) in enumerate(vocab_tokens):
vocab[token] = i
self.assertAllEqual(
tokenization.convert_tokens_to_ids(
vocab, ["un", "##want", "##ed", "runn", "##ing"]), [7, 4, 5, 8, 9])
def test_is_whitespace(self):
self.assertTrue(tokenization._is_whitespace(u" "))
self.assertTrue(tokenization._is_whitespace(u"\t"))
self.assertTrue(tokenization._is_whitespace(u"\r"))
self.assertTrue(tokenization._is_whitespace(u"\n"))
self.assertTrue(tokenization._is_whitespace(u"\u00A0"))
self.assertFalse(tokenization._is_whitespace(u"A"))
self.assertFalse(tokenization._is_whitespace(u"-"))
def test_is_control(self):
self.assertTrue(tokenization._is_control(u"\u0005"))
self.assertFalse(tokenization._is_control(u"A"))
self.assertFalse(tokenization._is_control(u" "))
self.assertFalse(tokenization._is_control(u"\t"))
self.assertFalse(tokenization._is_control(u"\r"))
self.assertFalse(tokenization._is_control(u"\U0001F4A9"))
def test_is_punctuation(self):
self.assertTrue(tokenization._is_punctuation(u"-"))
self.assertTrue(tokenization._is_punctuation(u"$"))
self.assertTrue(tokenization._is_punctuation(u"`"))
self.assertTrue(tokenization._is_punctuation(u"."))
self.assertFalse(tokenization._is_punctuation(u"A"))
self.assertFalse(tokenization._is_punctuation(u" "))
if __name__ == "__main__":
tf.test.main()
| 4,589 | 32.26087 | 80 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/run_pretraining.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run masked LM/next sentence masked_lm pre-training for BERT."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import modeling
import optimization
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_string(
"input_file", None,
"Input TF example files (can be a glob or comma separated).")
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written.")
## Other parameters
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_integer(
"max_seq_length", 128,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded. Must match data generation.")
flags.DEFINE_integer(
"max_predictions_per_seq", 20,
"Maximum number of masked LM predictions per sequence. "
"Must match data generation.")
flags.DEFINE_bool("do_train", False, "Whether to run training.")
flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
flags.DEFINE_integer("num_train_steps", 100000, "Number of training steps.")
flags.DEFINE_integer("num_warmup_steps", 10000, "Number of warmup steps.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_integer("max_eval_steps", 100, "Maximum number of eval steps.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
tf.flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
tf.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
def model_fn_builder(bert_config, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
masked_lm_positions = features["masked_lm_positions"]
masked_lm_ids = features["masked_lm_ids"]
masked_lm_weights = features["masked_lm_weights"]
next_sentence_labels = features["next_sentence_labels"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
(masked_lm_loss,
masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output(
bert_config, model.get_sequence_output(), model.get_embedding_table(),
masked_lm_positions, masked_lm_ids, masked_lm_weights)
(next_sentence_loss, next_sentence_example_loss,
next_sentence_log_probs) = get_next_sentence_output(
bert_config, model.get_pooled_output(), next_sentence_labels)
total_loss = masked_lm_loss + next_sentence_loss
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
masked_lm_weights, next_sentence_example_loss,
next_sentence_log_probs, next_sentence_labels):
"""Computes the loss and accuracy of the model."""
masked_lm_log_probs = tf.reshape(masked_lm_log_probs,
[-1, masked_lm_log_probs.shape[-1]])
masked_lm_predictions = tf.argmax(
masked_lm_log_probs, axis=-1, output_type=tf.int32)
masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
masked_lm_accuracy = tf.metrics.accuracy(
labels=masked_lm_ids,
predictions=masked_lm_predictions,
weights=masked_lm_weights)
masked_lm_mean_loss = tf.metrics.mean(
values=masked_lm_example_loss, weights=masked_lm_weights)
next_sentence_log_probs = tf.reshape(
next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
next_sentence_predictions = tf.argmax(
next_sentence_log_probs, axis=-1, output_type=tf.int32)
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
labels=next_sentence_labels, predictions=next_sentence_predictions)
next_sentence_mean_loss = tf.metrics.mean(
values=next_sentence_example_loss)
return {
"masked_lm_accuracy": masked_lm_accuracy,
"masked_lm_loss": masked_lm_mean_loss,
"next_sentence_accuracy": next_sentence_accuracy,
"next_sentence_loss": next_sentence_mean_loss,
}
eval_metrics = (metric_fn, [
masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
masked_lm_weights, next_sentence_example_loss,
next_sentence_log_probs, next_sentence_labels
])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode))
return output_spec
return model_fn
def get_masked_lm_output(bert_config, input_tensor, output_weights, positions,
label_ids, label_weights):
"""Get loss and log probs for the masked LM."""
input_tensor = gather_indexes(input_tensor, positions)
with tf.variable_scope("cls/predictions"):
# We apply one more non-linear transformation before the output layer.
# This matrix is not used after pre-training.
with tf.variable_scope("transform"):
input_tensor = tf.layers.dense(
input_tensor,
units=bert_config.hidden_size,
activation=modeling.get_activation(bert_config.hidden_act),
kernel_initializer=modeling.create_initializer(
bert_config.initializer_range))
input_tensor = modeling.layer_norm(input_tensor)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
output_bias = tf.get_variable(
"output_bias",
shape=[bert_config.vocab_size],
initializer=tf.zeros_initializer())
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
label_ids = tf.reshape(label_ids, [-1])
label_weights = tf.reshape(label_weights, [-1])
one_hot_labels = tf.one_hot(
label_ids, depth=bert_config.vocab_size, dtype=tf.float32)
# The `positions` tensor might be zero-padded (if the sequence is too
# short to have the maximum number of predictions). The `label_weights`
# tensor has a value of 1.0 for every real prediction and 0.0 for the
# padding predictions.
per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1])
numerator = tf.reduce_sum(label_weights * per_example_loss)
denominator = tf.reduce_sum(label_weights) + 1e-5
loss = numerator / denominator
return (loss, per_example_loss, log_probs)
def get_next_sentence_output(bert_config, input_tensor, labels):
"""Get loss and log probs for the next sentence prediction."""
# Simple binary classification. Note that 0 is "next sentence" and 1 is
# "random sentence". This weight matrix is not used after pre-training.
with tf.variable_scope("cls/seq_relationship"):
output_weights = tf.get_variable(
"output_weights",
shape=[2, bert_config.hidden_size],
initializer=modeling.create_initializer(bert_config.initializer_range))
output_bias = tf.get_variable(
"output_bias", shape=[2], initializer=tf.zeros_initializer())
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
labels = tf.reshape(labels, [-1])
one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, log_probs)
def gather_indexes(sequence_tensor, positions):
"""Gathers the vectors at the specific positions over a minibatch."""
sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3)
batch_size = sequence_shape[0]
seq_length = sequence_shape[1]
width = sequence_shape[2]
flat_offsets = tf.reshape(
tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])
flat_positions = tf.reshape(positions + flat_offsets, [-1])
flat_sequence_tensor = tf.reshape(sequence_tensor,
[batch_size * seq_length, width])
output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
return output_tensor
def input_fn_builder(input_files,
max_seq_length,
max_predictions_per_seq,
is_training,
num_cpu_threads=4):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
name_to_features = {
"input_ids":
tf.FixedLenFeature([max_seq_length], tf.int64),
"input_mask":
tf.FixedLenFeature([max_seq_length], tf.int64),
"segment_ids":
tf.FixedLenFeature([max_seq_length], tf.int64),
"masked_lm_positions":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_ids":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_weights":
tf.FixedLenFeature([max_predictions_per_seq], tf.float32),
"next_sentence_labels":
tf.FixedLenFeature([1], tf.int64),
}
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
if is_training:
d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
d = d.repeat()
d = d.shuffle(buffer_size=len(input_files))
# `cycle_length` is the number of parallel files that get read.
cycle_length = min(num_cpu_threads, len(input_files))
# `sloppy` mode means that the interleaving is not exact. This adds
# even more randomness to the training pipeline.
d = d.apply(
tf.contrib.data.parallel_interleave(
tf.data.TFRecordDataset,
sloppy=is_training,
cycle_length=cycle_length))
d = d.shuffle(buffer_size=100)
else:
d = tf.data.TFRecordDataset(input_files)
# Since we evaluate for a fixed number of steps we don't want to encounter
# out-of-range exceptions.
d = d.repeat()
# We must `drop_remainder` on training because the TPU requires fixed
# size dimensions. For eval, we assume we are evaluating on the CPU or GPU
# and we *don't* want to drop the remainder, otherwise we wont cover
# every sample.
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
num_parallel_batches=num_cpu_threads,
drop_remainder=True))
return d
return input_fn
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
if not FLAGS.do_train and not FLAGS.do_eval:
raise ValueError("At least one of `do_train` or `do_eval` must be True.")
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
tf.gfile.MakeDirs(FLAGS.output_dir)
input_files = []
for input_pattern in FLAGS.input_file.split(","):
input_files.extend(tf.gfile.Glob(input_pattern))
tf.logging.info("*** Input Files ***")
for input_file in input_files:
tf.logging.info(" %s" % input_file)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
model_fn = model_fn_builder(
bert_config=bert_config,
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=FLAGS.num_train_steps,
num_warmup_steps=FLAGS.num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size)
if FLAGS.do_train:
tf.logging.info("***** Running training *****")
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
train_input_fn = input_fn_builder(
input_files=input_files,
max_seq_length=FLAGS.max_seq_length,
max_predictions_per_seq=FLAGS.max_predictions_per_seq,
is_training=True)
estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps)
if FLAGS.do_eval:
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
eval_input_fn = input_fn_builder(
input_files=input_files,
max_seq_length=FLAGS.max_seq_length,
max_predictions_per_seq=FLAGS.max_predictions_per_seq,
is_training=False)
result = estimator.evaluate(
input_fn=eval_input_fn, steps=FLAGS.max_eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if __name__ == "__main__":
flags.mark_flag_as_required("input_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| 18,667 | 36.789474 | 82 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/__init__.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| 616 | 37.5625 | 74 | py |
CLUE | CLUE-master/baselines/models/roberta_wwm_ext/create_pretraining_data.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create masked LM/next sentence masked_lm TF examples for BERT."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import random
import tokenization
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_string("input_file", None,
"Input raw text file (or comma-separated list of files).")
flags.DEFINE_string(
"output_file", None,
"Output TF example file (or comma-separated list of files).")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_bool(
"do_whole_word_mask", False,
"Whether to use whole word masking rather than per-WordPiece masking.")
flags.DEFINE_integer("max_seq_length", 128, "Maximum sequence length.")
flags.DEFINE_integer("max_predictions_per_seq", 20,
"Maximum number of masked LM predictions per sequence.")
flags.DEFINE_integer("random_seed", 12345, "Random seed for data generation.")
flags.DEFINE_integer(
"dupe_factor", 10,
"Number of times to duplicate the input data (with different masks).")
flags.DEFINE_float("masked_lm_prob", 0.15, "Masked LM probability.")
flags.DEFINE_float(
"short_seq_prob", 0.1,
"Probability of creating sequences which are shorter than the "
"maximum length.")
class TrainingInstance(object):
"""A single training instance (sentence pair)."""
def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels,
is_random_next):
self.tokens = tokens
self.segment_ids = segment_ids
self.is_random_next = is_random_next
self.masked_lm_positions = masked_lm_positions
self.masked_lm_labels = masked_lm_labels
def __str__(self):
s = ""
s += "tokens: %s\n" % (" ".join(
[tokenization.printable_text(x) for x in self.tokens]))
s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids]))
s += "is_random_next: %s\n" % self.is_random_next
s += "masked_lm_positions: %s\n" % (" ".join(
[str(x) for x in self.masked_lm_positions]))
s += "masked_lm_labels: %s\n" % (" ".join(
[tokenization.printable_text(x) for x in self.masked_lm_labels]))
s += "\n"
return s
def __repr__(self):
return self.__str__()
def write_instance_to_example_files(instances, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
"""Create TF example files from `TrainingInstance`s."""
writers = []
for output_file in output_files:
writers.append(tf.python_io.TFRecordWriter(output_file))
writer_index = 0
total_written = 0
for (inst_index, instance) in enumerate(instances):
input_ids = tokenizer.convert_tokens_to_ids(instance.tokens)
input_mask = [1] * len(input_ids)
segment_ids = list(instance.segment_ids)
assert len(input_ids) <= max_seq_length
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
masked_lm_positions = list(instance.masked_lm_positions)
masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels)
masked_lm_weights = [1.0] * len(masked_lm_ids)
while len(masked_lm_positions) < max_predictions_per_seq:
masked_lm_positions.append(0)
masked_lm_ids.append(0)
masked_lm_weights.append(0.0)
next_sentence_label = 1 if instance.is_random_next else 0
features = collections.OrderedDict()
features["input_ids"] = create_int_feature(input_ids)
features["input_mask"] = create_int_feature(input_mask)
features["segment_ids"] = create_int_feature(segment_ids)
features["masked_lm_positions"] = create_int_feature(masked_lm_positions)
features["masked_lm_ids"] = create_int_feature(masked_lm_ids)
features["masked_lm_weights"] = create_float_feature(masked_lm_weights)
features["next_sentence_labels"] = create_int_feature([next_sentence_label])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writers[writer_index].write(tf_example.SerializeToString())
writer_index = (writer_index + 1) % len(writers)
total_written += 1
if inst_index < 20:
tf.logging.info("*** Example ***")
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in instance.tokens]))
for feature_name in features.keys():
feature = features[feature_name]
values = []
if feature.int64_list.value:
values = feature.int64_list.value
elif feature.float_list.value:
values = feature.float_list.value
tf.logging.info(
"%s: %s" % (feature_name, " ".join([str(x) for x in values])))
for writer in writers:
writer.close()
tf.logging.info("Wrote %d total instances", total_written)
def create_int_feature(values):
feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return feature
def create_float_feature(values):
feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
return feature
def create_training_instances(input_files, tokenizer, max_seq_length,
dupe_factor, short_seq_prob, masked_lm_prob,
max_predictions_per_seq, rng):
"""Create `TrainingInstance`s from raw text."""
all_documents = [[]]
# Input file format:
# (1) One sentence per line. These should ideally be actual sentences, not
# entire paragraphs or arbitrary spans of text. (Because we use the
# sentence boundaries for the "next sentence prediction" task).
# (2) Blank lines between documents. Document boundaries are needed so
# that the "next sentence prediction" task doesn't span between documents.
for input_file in input_files:
with tf.gfile.GFile(input_file, "r") as reader:
while True:
line = tokenization.convert_to_unicode(reader.readline())
if not line:
break
line = line.strip()
# Empty lines are used as document delimiters
if not line:
all_documents.append([])
tokens = tokenizer.tokenize(line)
if tokens:
all_documents[-1].append(tokens)
# Remove empty documents
all_documents = [x for x in all_documents if x]
rng.shuffle(all_documents)
vocab_words = list(tokenizer.vocab.keys())
instances = []
for _ in range(dupe_factor):
for document_index in range(len(all_documents)):
instances.extend(
create_instances_from_document(
all_documents, document_index, max_seq_length, short_seq_prob,
masked_lm_prob, max_predictions_per_seq, vocab_words, rng))
rng.shuffle(instances)
return instances
def create_instances_from_document(
all_documents, document_index, max_seq_length, short_seq_prob,
masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
"""Creates `TrainingInstance`s for a single document."""
document = all_documents[document_index]
# Account for [CLS], [SEP], [SEP]
max_num_tokens = max_seq_length - 3
# We *usually* want to fill up the entire sequence since we are padding
# to `max_seq_length` anyways, so short sequences are generally wasted
# computation. However, we *sometimes*
# (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter
# sequences to minimize the mismatch between pre-training and fine-tuning.
# The `target_seq_length` is just a rough target however, whereas
# `max_seq_length` is a hard limit.
target_seq_length = max_num_tokens
if rng.random() < short_seq_prob:
target_seq_length = rng.randint(2, max_num_tokens)
# We DON'T just concatenate all of the tokens from a document into a long
# sequence and choose an arbitrary split point because this would make the
# next sentence prediction task too easy. Instead, we split the input into
# segments "A" and "B" based on the actual "sentences" provided by the user
# input.
instances = []
current_chunk = []
current_length = 0
i = 0
while i < len(document):
segment = document[i]
current_chunk.append(segment)
current_length += len(segment)
if i == len(document) - 1 or current_length >= target_seq_length:
if current_chunk:
# `a_end` is how many segments from `current_chunk` go into the `A`
# (first) sentence.
a_end = 1
if len(current_chunk) >= 2:
a_end = rng.randint(1, len(current_chunk) - 1)
tokens_a = []
for j in range(a_end):
tokens_a.extend(current_chunk[j])
tokens_b = []
# Random next
is_random_next = False
if len(current_chunk) == 1 or rng.random() < 0.5:
is_random_next = True
target_b_length = target_seq_length - len(tokens_a)
# This should rarely go for more than one iteration for large
# corpora. However, just to be careful, we try to make sure that
# the random document is not the same as the document
# we're processing.
for _ in range(10):
random_document_index = rng.randint(0, len(all_documents) - 1)
if random_document_index != document_index:
break
random_document = all_documents[random_document_index]
random_start = rng.randint(0, len(random_document) - 1)
for j in range(random_start, len(random_document)):
tokens_b.extend(random_document[j])
if len(tokens_b) >= target_b_length:
break
# We didn't actually use these segments so we "put them back" so
# they don't go to waste.
num_unused_segments = len(current_chunk) - a_end
i -= num_unused_segments
# Actual next
else:
is_random_next = False
for j in range(a_end, len(current_chunk)):
tokens_b.extend(current_chunk[j])
truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng)
assert len(tokens_a) >= 1
assert len(tokens_b) >= 1
tokens = []
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in tokens_a:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
for token in tokens_b:
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
(tokens, masked_lm_positions,
masked_lm_labels) = create_masked_lm_predictions(
tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng)
instance = TrainingInstance(
tokens=tokens,
segment_ids=segment_ids,
is_random_next=is_random_next,
masked_lm_positions=masked_lm_positions,
masked_lm_labels=masked_lm_labels)
instances.append(instance)
current_chunk = []
current_length = 0
i += 1
return instances
MaskedLmInstance = collections.namedtuple("MaskedLmInstance",
["index", "label"])
def create_masked_lm_predictions(tokens, masked_lm_prob,
max_predictions_per_seq, vocab_words, rng):
"""Creates the predictions for the masked LM objective."""
cand_indexes = []
for (i, token) in enumerate(tokens):
if token == "[CLS]" or token == "[SEP]":
continue
# Whole Word Masking means that if we mask all of the wordpieces
# corresponding to an original word. When a word has been split into
# WordPieces, the first token does not have any marker and any subsequence
# tokens are prefixed with ##. So whenever we see the ## token, we
# append it to the previous set of word indexes.
#
# Note that Whole Word Masking does *not* change the training code
# at all -- we still predict each WordPiece independently, softmaxed
# over the entire vocabulary.
if (FLAGS.do_whole_word_mask and len(cand_indexes) >= 1 and
token.startswith("##")):
cand_indexes[-1].append(i)
else:
cand_indexes.append([i])
rng.shuffle(cand_indexes)
output_tokens = list(tokens)
num_to_predict = min(max_predictions_per_seq,
max(1, int(round(len(tokens) * masked_lm_prob))))
masked_lms = []
covered_indexes = set()
for index_set in cand_indexes:
if len(masked_lms) >= num_to_predict:
break
# If adding a whole-word mask would exceed the maximum number of
# predictions, then just skip this candidate.
if len(masked_lms) + len(index_set) > num_to_predict:
continue
is_any_index_covered = False
for index in index_set:
if index in covered_indexes:
is_any_index_covered = True
break
if is_any_index_covered:
continue
for index in index_set:
covered_indexes.add(index)
masked_token = None
# 80% of the time, replace with [MASK]
if rng.random() < 0.8:
masked_token = "[MASK]"
else:
# 10% of the time, keep original
if rng.random() < 0.5:
masked_token = tokens[index]
# 10% of the time, replace with random word
else:
masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)]
output_tokens[index] = masked_token
masked_lms.append(MaskedLmInstance(index=index, label=tokens[index]))
assert len(masked_lms) <= num_to_predict
masked_lms = sorted(masked_lms, key=lambda x: x.index)
masked_lm_positions = []
masked_lm_labels = []
for p in masked_lms:
masked_lm_positions.append(p.index)
masked_lm_labels.append(p.label)
return (output_tokens, masked_lm_positions, masked_lm_labels)
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
"""Truncates a pair of sequences to a maximum sequence length."""
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_num_tokens:
break
trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b
assert len(trunc_tokens) >= 1
# We want to sometimes truncate from the front and sometimes from the
# back to add more randomness and avoid biases.
if rng.random() < 0.5:
del trunc_tokens[0]
else:
trunc_tokens.pop()
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
input_files = []
for input_pattern in FLAGS.input_file.split(","):
input_files.extend(tf.gfile.Glob(input_pattern))
tf.logging.info("*** Reading from input files ***")
for input_file in input_files:
tf.logging.info(" %s", input_file)
rng = random.Random(FLAGS.random_seed)
instances = create_training_instances(
input_files, tokenizer, FLAGS.max_seq_length, FLAGS.dupe_factor,
FLAGS.short_seq_prob, FLAGS.masked_lm_prob, FLAGS.max_predictions_per_seq,
rng)
output_files = FLAGS.output_file.split(",")
tf.logging.info("*** Writing to output files ***")
for output_file in output_files:
tf.logging.info(" %s", output_file)
write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length,
FLAGS.max_predictions_per_seq, output_files)
if __name__ == "__main__":
flags.mark_flag_as_required("input_file")
flags.mark_flag_as_required("output_file")
flags.mark_flag_as_required("vocab_file")
tf.app.run()
| 16,475 | 34.055319 | 80 | py |
CLUE | CLUE-master/baselines/models/ernie/run_classifier_with_tfhub.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BERT finetuning runner with TF-Hub."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import optimization
import run_classifier
import tokenization
import tensorflow as tf
import tensorflow_hub as hub
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_string(
"bert_hub_module_handle", None,
"Handle for the BERT TF-Hub module.")
def create_model(is_training, input_ids, input_mask, segment_ids, labels,
num_labels, bert_hub_module_handle):
"""Creates a classification model."""
tags = set()
if is_training:
tags.add("train")
bert_module = hub.Module(bert_hub_module_handle, tags=tags, trainable=True)
bert_inputs = dict(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids)
bert_outputs = bert_module(
inputs=bert_inputs,
signature="tokens",
as_dict=True)
# In the demo, we are doing a simple classification task on the entire
# segment.
#
# If you want to use the token-level output, use
# bert_outputs["sequence_output"] instead.
output_layer = bert_outputs["pooled_output"]
hidden_size = output_layer.shape[-1].value
output_weights = tf.get_variable(
"output_weights", [num_labels, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer())
with tf.variable_scope("loss"):
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax(logits, axis=-1)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, logits, probabilities)
def model_fn_builder(num_labels, learning_rate, num_train_steps,
num_warmup_steps, use_tpu, bert_hub_module_handle):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(total_loss, per_example_loss, logits, probabilities) = create_model(
is_training, input_ids, input_mask, segment_ids, label_ids, num_labels,
bert_hub_module_handle)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
accuracy = tf.metrics.accuracy(label_ids, predictions)
loss = tf.metrics.mean(per_example_loss)
return {
"eval_accuracy": accuracy,
"eval_loss": loss,
}
eval_metrics = (metric_fn, [per_example_loss, label_ids, logits])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics)
elif mode == tf.estimator.ModeKeys.PREDICT:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions={"probabilities": probabilities})
else:
raise ValueError(
"Only TRAIN, EVAL and PREDICT modes are supported: %s" % (mode))
return output_spec
return model_fn
def create_tokenizer_from_hub_module(bert_hub_module_handle):
"""Get the vocab file and casing info from the Hub module."""
with tf.Graph().as_default():
bert_module = hub.Module(bert_hub_module_handle)
tokenization_info = bert_module(signature="tokenization_info", as_dict=True)
with tf.Session() as sess:
vocab_file, do_lower_case = sess.run([tokenization_info["vocab_file"],
tokenization_info["do_lower_case"]])
return tokenization.FullTokenizer(
vocab_file=vocab_file, do_lower_case=do_lower_case)
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"cola": run_classifier.ColaProcessor,
"mnli": run_classifier.MnliProcessor,
"mrpc": run_classifier.MrpcProcessor,
}
if not FLAGS.do_train and not FLAGS.do_eval:
raise ValueError("At least one of `do_train` or `do_eval` must be True.")
tf.gfile.MakeDirs(FLAGS.output_dir)
task_name = FLAGS.task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
label_list = processor.get_labels()
tokenizer = create_tokenizer_from_hub_module(FLAGS.bert_hub_module_handle)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = processor.get_train_examples(FLAGS.data_dir)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
model_fn = model_fn_builder(
num_labels=len(label_list),
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
bert_hub_module_handle=FLAGS.bert_hub_module_handle)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
train_features = run_classifier.convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = run_classifier.input_fn_builder(
features=train_features,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_eval:
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
eval_features = run_classifier.convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d", len(eval_examples))
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
# This tells the estimator to run through the entire set.
eval_steps = None
# However, if running eval on the TPU, you will need to specify the
# number of steps.
if FLAGS.use_tpu:
# Eval will be slightly WRONG on the TPU because it will truncate
# the last batch.
eval_steps = int(len(eval_examples) / FLAGS.eval_batch_size)
eval_drop_remainder = True if FLAGS.use_tpu else False
eval_input_fn = run_classifier.input_fn_builder(
features=eval_features,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=eval_drop_remainder)
result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_predict:
predict_examples = processor.get_test_examples(FLAGS.data_dir)
if FLAGS.use_tpu:
# Discard batch remainder if running on TPU
n = len(predict_examples)
predict_examples = predict_examples[:(n - n % FLAGS.predict_batch_size)]
predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
run_classifier.file_based_convert_examples_to_features(
predict_examples, label_list, FLAGS.max_seq_length, tokenizer,
predict_file)
tf.logging.info("***** Running prediction*****")
tf.logging.info(" Num examples = %d", len(predict_examples))
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
predict_input_fn = run_classifier.file_based_input_fn_builder(
input_file=predict_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=FLAGS.use_tpu)
result = estimator.predict(input_fn=predict_input_fn)
output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
with tf.gfile.GFile(output_predict_file, "w") as writer:
tf.logging.info("***** Predict results *****")
for prediction in result:
probabilities = prediction["probabilities"]
output_line = "\t".join(
str(class_probability)
for class_probability in probabilities) + "\n"
writer.write(output_line)
if __name__ == "__main__":
flags.mark_flag_as_required("data_dir")
flags.mark_flag_as_required("task_name")
flags.mark_flag_as_required("bert_hub_module_handle")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| 11,426 | 35.27619 | 82 | py |
CLUE | CLUE-master/baselines/models/ernie/optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Functions and classes related to optimization (weight updates)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import tensorflow as tf
def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu):
"""Creates an optimizer training op."""
global_step = tf.train.get_or_create_global_step()
learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32)
# Implements linear decay of the learning rate.
learning_rate = tf.train.polynomial_decay(
learning_rate,
global_step,
num_train_steps,
end_learning_rate=0.0,
power=1.0,
cycle=False)
# Implements linear warmup. I.e., if global_step < num_warmup_steps, the
# learning rate will be `global_step/num_warmup_steps * init_lr`.
if num_warmup_steps:
global_steps_int = tf.cast(global_step, tf.int32)
warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32)
global_steps_float = tf.cast(global_steps_int, tf.float32)
warmup_steps_float = tf.cast(warmup_steps_int, tf.float32)
warmup_percent_done = global_steps_float / warmup_steps_float
warmup_learning_rate = init_lr * warmup_percent_done
is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32)
learning_rate = (
(1.0 - is_warmup) * learning_rate + is_warmup * warmup_learning_rate)
# It is recommended that you use this optimizer for fine tuning, since this
# is how the model was trained (note that the Adam m/v variables are NOT
# loaded from init_checkpoint.)
optimizer = AdamWeightDecayOptimizer(
learning_rate=learning_rate,
weight_decay_rate=0.01,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-6,
exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"])
if use_tpu:
optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
tvars = tf.trainable_variables()
grads = tf.gradients(loss, tvars)
# This is how the model was pre-trained.
(grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0)
train_op = optimizer.apply_gradients(
zip(grads, tvars), global_step=global_step)
# Normally the global step update is done inside of `apply_gradients`.
# However, `AdamWeightDecayOptimizer` doesn't do this. But if you use
# a different optimizer, you should probably take this line out.
new_global_step = global_step + 1
train_op = tf.group(train_op, [global_step.assign(new_global_step)])
return train_op
class AdamWeightDecayOptimizer(tf.train.Optimizer):
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self,
learning_rate,
weight_decay_rate=0.0,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-6,
exclude_from_weight_decay=None,
name="AdamWeightDecayOptimizer"):
"""Constructs a AdamWeightDecayOptimizer."""
super(AdamWeightDecayOptimizer, self).__init__(False, name)
self.learning_rate = learning_rate
self.weight_decay_rate = weight_decay_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
self.exclude_from_weight_decay = exclude_from_weight_decay
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""See base class."""
assignments = []
for (grad, param) in grads_and_vars:
if grad is None or param is None:
continue
param_name = self._get_variable_name(param.name)
m = tf.get_variable(
name=param_name + "/adam_m",
shape=param.shape.as_list(),
dtype=tf.float32,
trainable=False,
initializer=tf.zeros_initializer())
v = tf.get_variable(
name=param_name + "/adam_v",
shape=param.shape.as_list(),
dtype=tf.float32,
trainable=False,
initializer=tf.zeros_initializer())
# Standard Adam update.
next_m = (
tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad))
next_v = (
tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2,
tf.square(grad)))
update = next_m / (tf.sqrt(next_v) + self.epsilon)
# Just adding the square of the weights to the loss function is *not*
# the correct way of using L2 regularization/weight decay with Adam,
# since that will interact with the m and v parameters in strange ways.
#
# Instead we want ot decay the weights in a manner that doesn't interact
# with the m/v parameters. This is equivalent to adding the square
# of the weights to the loss with plain (non-momentum) SGD.
if self._do_use_weight_decay(param_name):
update += self.weight_decay_rate * param
update_with_lr = self.learning_rate * update
next_param = param - update_with_lr
assignments.extend(
[param.assign(next_param),
m.assign(next_m),
v.assign(next_v)])
return tf.group(*assignments, name=name)
def _do_use_weight_decay(self, param_name):
"""Whether to use L2 weight decay for `param_name`."""
if not self.weight_decay_rate:
return False
if self.exclude_from_weight_decay:
for r in self.exclude_from_weight_decay:
if re.search(r, param_name) is not None:
return False
return True
def _get_variable_name(self, param_name):
"""Get the variable name from the tensor name."""
m = re.match("^(.*):\\d+$", param_name)
if m is not None:
param_name = m.group(1)
return param_name
| 6,258 | 34.765714 | 80 | py |
CLUE | CLUE-master/baselines/models/ernie/run_squad.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run BERT on SQuAD 1.1 and SQuAD 2.0."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import json
import math
import os
import random
import modeling
import optimization
import tokenization
import six
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written.")
## Other parameters
flags.DEFINE_string("train_file", None,
"SQuAD json for training. E.g., train-v1.1.json")
flags.DEFINE_string(
"predict_file", None,
"SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json")
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_integer(
"max_seq_length", 384,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded.")
flags.DEFINE_integer(
"doc_stride", 128,
"When splitting up a long document into chunks, how much stride to "
"take between chunks.")
flags.DEFINE_integer(
"max_query_length", 64,
"The maximum number of tokens for the question. Questions longer than "
"this will be truncated to this length.")
flags.DEFINE_bool("do_train", False, "Whether to run training.")
flags.DEFINE_bool("do_predict", False, "Whether to run eval on the dev set.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("predict_batch_size", 8,
"Total batch size for predictions.")
flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
flags.DEFINE_float("num_train_epochs", 3.0,
"Total number of training epochs to perform.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_integer(
"n_best_size", 20,
"The total number of n-best predictions to generate in the "
"nbest_predictions.json output file.")
flags.DEFINE_integer(
"max_answer_length", 30,
"The maximum length of an answer that can be generated. This is needed "
"because the start and end predictions are not conditioned on one another.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
tf.flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
tf.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
flags.DEFINE_bool(
"verbose_logging", False,
"If true, all of the warnings related to data processing will be printed. "
"A number of warnings are expected for a normal SQuAD evaluation.")
flags.DEFINE_bool(
"version_2_with_negative", False,
"If true, the SQuAD examples contain some that do not have an answer.")
flags.DEFINE_float(
"null_score_diff_threshold", 0.0,
"If null_score - best_non_null is greater than the threshold predict null.")
class SquadExample(object):
"""A single training/test example for simple sequence classification.
For examples without an answer, the start and end position are -1.
"""
def __init__(self,
qas_id,
question_text,
doc_tokens,
orig_answer_text=None,
start_position=None,
end_position=None,
is_impossible=False):
self.qas_id = qas_id
self.question_text = question_text
self.doc_tokens = doc_tokens
self.orig_answer_text = orig_answer_text
self.start_position = start_position
self.end_position = end_position
self.is_impossible = is_impossible
def __str__(self):
return self.__repr__()
def __repr__(self):
s = ""
s += "qas_id: %s" % (tokenization.printable_text(self.qas_id))
s += ", question_text: %s" % (
tokenization.printable_text(self.question_text))
s += ", doc_tokens: [%s]" % (" ".join(self.doc_tokens))
if self.start_position:
s += ", start_position: %d" % (self.start_position)
if self.start_position:
s += ", end_position: %d" % (self.end_position)
if self.start_position:
s += ", is_impossible: %r" % (self.is_impossible)
return s
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
unique_id,
example_index,
doc_span_index,
tokens,
token_to_orig_map,
token_is_max_context,
input_ids,
input_mask,
segment_ids,
start_position=None,
end_position=None,
is_impossible=None):
self.unique_id = unique_id
self.example_index = example_index
self.doc_span_index = doc_span_index
self.tokens = tokens
self.token_to_orig_map = token_to_orig_map
self.token_is_max_context = token_is_max_context
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.start_position = start_position
self.end_position = end_position
self.is_impossible = is_impossible
def read_squad_examples(input_file, is_training):
"""Read a SQuAD json file into a list of SquadExample."""
with tf.gfile.Open(input_file, "r") as reader:
input_data = json.load(reader)["data"]
def is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
examples = []
for entry in input_data:
for paragraph in entry["paragraphs"]:
paragraph_text = paragraph["context"]
doc_tokens = []
char_to_word_offset = []
prev_is_whitespace = True
for c in paragraph_text:
if is_whitespace(c):
prev_is_whitespace = True
else:
if prev_is_whitespace:
doc_tokens.append(c)
else:
doc_tokens[-1] += c
prev_is_whitespace = False
char_to_word_offset.append(len(doc_tokens) - 1)
for qa in paragraph["qas"]:
qas_id = qa["id"]
question_text = qa["question"]
start_position = None
end_position = None
orig_answer_text = None
is_impossible = False
if is_training:
if FLAGS.version_2_with_negative:
is_impossible = qa["is_impossible"]
if (len(qa["answers"]) != 1) and (not is_impossible):
raise ValueError(
"For training, each question should have exactly 1 answer.")
if not is_impossible:
answer = qa["answers"][0]
orig_answer_text = answer["text"]
answer_offset = answer["answer_start"]
answer_length = len(orig_answer_text)
start_position = char_to_word_offset[answer_offset]
end_position = char_to_word_offset[answer_offset + answer_length -
1]
# Only add answers where the text can be exactly recovered from the
# document. If this CAN'T happen it's likely due to weird Unicode
# stuff so we will just skip the example.
#
# Note that this means for training mode, every example is NOT
# guaranteed to be preserved.
actual_text = " ".join(
doc_tokens[start_position:(end_position + 1)])
cleaned_answer_text = " ".join(
tokenization.whitespace_tokenize(orig_answer_text))
if actual_text.find(cleaned_answer_text) == -1:
tf.logging.warning("Could not find answer: '%s' vs. '%s'",
actual_text, cleaned_answer_text)
continue
else:
start_position = -1
end_position = -1
orig_answer_text = ""
example = SquadExample(
qas_id=qas_id,
question_text=question_text,
doc_tokens=doc_tokens,
orig_answer_text=orig_answer_text,
start_position=start_position,
end_position=end_position,
is_impossible=is_impossible)
examples.append(example)
return examples
def convert_examples_to_features(examples, tokenizer, max_seq_length,
doc_stride, max_query_length, is_training,
output_fn):
"""Loads a data file into a list of `InputBatch`s."""
unique_id = 1000000000
for (example_index, example) in enumerate(examples):
query_tokens = tokenizer.tokenize(example.question_text)
if len(query_tokens) > max_query_length:
query_tokens = query_tokens[0:max_query_length]
tok_to_orig_index = []
orig_to_tok_index = []
all_doc_tokens = []
for (i, token) in enumerate(example.doc_tokens):
orig_to_tok_index.append(len(all_doc_tokens))
sub_tokens = tokenizer.tokenize(token)
for sub_token in sub_tokens:
tok_to_orig_index.append(i)
all_doc_tokens.append(sub_token)
tok_start_position = None
tok_end_position = None
if is_training and example.is_impossible:
tok_start_position = -1
tok_end_position = -1
if is_training and not example.is_impossible:
tok_start_position = orig_to_tok_index[example.start_position]
if example.end_position < len(example.doc_tokens) - 1:
tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
else:
tok_end_position = len(all_doc_tokens) - 1
(tok_start_position, tok_end_position) = _improve_answer_span(
all_doc_tokens, tok_start_position, tok_end_position, tokenizer,
example.orig_answer_text)
# The -3 accounts for [CLS], [SEP] and [SEP]
max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
# We can have documents that are longer than the maximum sequence length.
# To deal with this we do a sliding window approach, where we take chunks
# of the up to our max length with a stride of `doc_stride`.
_DocSpan = collections.namedtuple( # pylint: disable=invalid-name
"DocSpan", ["start", "length"])
doc_spans = []
start_offset = 0
while start_offset < len(all_doc_tokens):
length = len(all_doc_tokens) - start_offset
if length > max_tokens_for_doc:
length = max_tokens_for_doc
doc_spans.append(_DocSpan(start=start_offset, length=length))
if start_offset + length == len(all_doc_tokens):
break
start_offset += min(length, doc_stride)
for (doc_span_index, doc_span) in enumerate(doc_spans):
tokens = []
token_to_orig_map = {}
token_is_max_context = {}
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
for i in range(doc_span.length):
split_token_index = doc_span.start + i
token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
is_max_context = _check_is_max_context(doc_spans, doc_span_index,
split_token_index)
token_is_max_context[len(tokens)] = is_max_context
tokens.append(all_doc_tokens[split_token_index])
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
start_position = None
end_position = None
if is_training and not example.is_impossible:
# For training, if our document chunk does not contain an annotation
# we throw it out, since there is nothing to predict.
doc_start = doc_span.start
doc_end = doc_span.start + doc_span.length - 1
out_of_span = False
if not (tok_start_position >= doc_start and
tok_end_position <= doc_end):
out_of_span = True
if out_of_span:
start_position = 0
end_position = 0
else:
doc_offset = len(query_tokens) + 2
start_position = tok_start_position - doc_start + doc_offset
end_position = tok_end_position - doc_start + doc_offset
if is_training and example.is_impossible:
start_position = 0
end_position = 0
if example_index < 20:
tf.logging.info("*** Example ***")
tf.logging.info("unique_id: %s" % (unique_id))
tf.logging.info("example_index: %s" % (example_index))
tf.logging.info("doc_span_index: %s" % (doc_span_index))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("token_to_orig_map: %s" % " ".join(
["%d:%d" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))
tf.logging.info("token_is_max_context: %s" % " ".join([
"%d:%s" % (x, y) for (x, y) in six.iteritems(token_is_max_context)
]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info(
"input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info(
"segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
if is_training and example.is_impossible:
tf.logging.info("impossible example")
if is_training and not example.is_impossible:
answer_text = " ".join(tokens[start_position:(end_position + 1)])
tf.logging.info("start_position: %d" % (start_position))
tf.logging.info("end_position: %d" % (end_position))
tf.logging.info(
"answer: %s" % (tokenization.printable_text(answer_text)))
feature = InputFeatures(
unique_id=unique_id,
example_index=example_index,
doc_span_index=doc_span_index,
tokens=tokens,
token_to_orig_map=token_to_orig_map,
token_is_max_context=token_is_max_context,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
start_position=start_position,
end_position=end_position,
is_impossible=example.is_impossible)
# Run callback
output_fn(feature)
unique_id += 1
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
orig_answer_text):
"""Returns tokenized answer spans that better match the annotated answer."""
# The SQuAD annotations are character based. We first project them to
# whitespace-tokenized words. But then after WordPiece tokenization, we can
# often find a "better match". For example:
#
# Question: What year was John Smith born?
# Context: The leader was John Smith (1895-1943).
# Answer: 1895
#
# The original whitespace-tokenized answer will be "(1895-1943).". However
# after tokenization, our tokens will be "( 1895 - 1943 ) .". So we can match
# the exact answer, 1895.
#
# However, this is not always possible. Consider the following:
#
# Question: What country is the top exporter of electornics?
# Context: The Japanese electronics industry is the lagest in the world.
# Answer: Japan
#
# In this case, the annotator chose "Japan" as a character sub-span of
# the word "Japanese". Since our WordPiece tokenizer does not split
# "Japanese", we just use "Japanese" as the annotation. This is fairly rare
# in SQuAD, but does happen.
tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
for new_start in range(input_start, input_end + 1):
for new_end in range(input_end, new_start - 1, -1):
text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
if text_span == tok_answer_text:
return (new_start, new_end)
return (input_start, input_end)
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a single
# token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a gallon of milk
# Span A: the man went to the
# Span B: to the store and bought
# Span C: and bought a gallon of
# ...
#
# Now the word 'bought' will have two scores from spans B and C. We only
# want to consider the score with "maximum context", which we define as
# the *minimum* of its left and right context (the *sum* of left and
# right context will always be the same, of course).
#
# In the example the maximum context for 'bought' would be span C since
# it has 1 left context and 3 right context, while span B has 4 left context
# and 0 right context.
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
use_one_hot_embeddings):
"""Creates a classification model."""
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
final_hidden = model.get_sequence_output()
final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)
batch_size = final_hidden_shape[0]
seq_length = final_hidden_shape[1]
hidden_size = final_hidden_shape[2]
output_weights = tf.get_variable(
"cls/squad/output_weights", [2, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"cls/squad/output_bias", [2], initializer=tf.zeros_initializer())
final_hidden_matrix = tf.reshape(final_hidden,
[batch_size * seq_length, hidden_size])
logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
logits = tf.reshape(logits, [batch_size, seq_length, 2])
logits = tf.transpose(logits, [2, 0, 1])
unstacked_logits = tf.unstack(logits, axis=0)
(start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])
return (start_logits, end_logits)
def model_fn_builder(bert_config, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
unique_ids = features["unique_ids"]
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(start_logits, end_logits) = create_model(
bert_config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
seq_length = modeling.get_shape_list(input_ids)[1]
def compute_loss(logits, positions):
one_hot_positions = tf.one_hot(
positions, depth=seq_length, dtype=tf.float32)
log_probs = tf.nn.log_softmax(logits, axis=-1)
loss = -tf.reduce_mean(
tf.reduce_sum(one_hot_positions * log_probs, axis=-1))
return loss
start_positions = features["start_positions"]
end_positions = features["end_positions"]
start_loss = compute_loss(start_logits, start_positions)
end_loss = compute_loss(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2.0
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
"unique_ids": unique_ids,
"start_logits": start_logits,
"end_logits": end_logits,
}
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
else:
raise ValueError(
"Only TRAIN and PREDICT modes are supported: %s" % (mode))
return output_spec
return model_fn
def input_fn_builder(input_file, seq_length, is_training, drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"unique_ids": tf.FixedLenFeature([], tf.int64),
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
}
if is_training:
name_to_features["start_positions"] = tf.FixedLenFeature([], tf.int64)
name_to_features["end_positions"] = tf.FixedLenFeature([], tf.int64)
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder))
return d
return input_fn
RawResult = collections.namedtuple("RawResult",
["unique_id", "start_logits", "end_logits"])
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, do_lower_case, output_prediction_file,
output_nbest_file, output_null_log_odds_file):
"""Write final predictions to the json file and log-odds of null if needed."""
tf.logging.info("Writing predictions to: %s" % (output_prediction_file))
tf.logging.info("Writing nbest to: %s" % (output_nbest_file))
example_index_to_features = collections.defaultdict(list)
for feature in all_features:
example_index_to_features[feature.example_index].append(feature)
unique_id_to_result = {}
for result in all_results:
unique_id_to_result[result.unique_id] = result
_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
"PrelimPrediction",
["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
all_predictions = collections.OrderedDict()
all_nbest_json = collections.OrderedDict()
scores_diff_json = collections.OrderedDict()
for (example_index, example) in enumerate(all_examples):
features = example_index_to_features[example_index]
prelim_predictions = []
# keep track of the minimum score of null start+end of position 0
score_null = 1000000 # large and positive
min_null_feature_index = 0 # the paragraph slice with min mull score
null_start_logit = 0 # the start logit at the slice with min null score
null_end_logit = 0 # the end logit at the slice with min null score
for (feature_index, feature) in enumerate(features):
result = unique_id_to_result[feature.unique_id]
start_indexes = _get_best_indexes(result.start_logits, n_best_size)
end_indexes = _get_best_indexes(result.end_logits, n_best_size)
# if we could have irrelevant answers, get the min score of irrelevant
if FLAGS.version_2_with_negative:
feature_null_score = result.start_logits[0] + result.end_logits[0]
if feature_null_score < score_null:
score_null = feature_null_score
min_null_feature_index = feature_index
null_start_logit = result.start_logits[0]
null_end_logit = result.end_logits[0]
for start_index in start_indexes:
for end_index in end_indexes:
# We could hypothetically create invalid predictions, e.g., predict
# that the start of the span is in the question. We throw out all
# invalid predictions.
if start_index >= len(feature.tokens):
continue
if end_index >= len(feature.tokens):
continue
if start_index not in feature.token_to_orig_map:
continue
if end_index not in feature.token_to_orig_map:
continue
if not feature.token_is_max_context.get(start_index, False):
continue
if end_index < start_index:
continue
length = end_index - start_index + 1
if length > max_answer_length:
continue
prelim_predictions.append(
_PrelimPrediction(
feature_index=feature_index,
start_index=start_index,
end_index=end_index,
start_logit=result.start_logits[start_index],
end_logit=result.end_logits[end_index]))
if FLAGS.version_2_with_negative:
prelim_predictions.append(
_PrelimPrediction(
feature_index=min_null_feature_index,
start_index=0,
end_index=0,
start_logit=null_start_logit,
end_logit=null_end_logit))
prelim_predictions = sorted(
prelim_predictions,
key=lambda x: (x.start_logit + x.end_logit),
reverse=True)
_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
"NbestPrediction", ["text", "start_logit", "end_logit"])
seen_predictions = {}
nbest = []
for pred in prelim_predictions:
if len(nbest) >= n_best_size:
break
feature = features[pred.feature_index]
if pred.start_index > 0: # this is a non-null prediction
tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]
orig_doc_start = feature.token_to_orig_map[pred.start_index]
orig_doc_end = feature.token_to_orig_map[pred.end_index]
orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]
tok_text = " ".join(tok_tokens)
# De-tokenize WordPieces that have been split off.
tok_text = tok_text.replace(" ##", "")
tok_text = tok_text.replace("##", "")
# Clean whitespace
tok_text = tok_text.strip()
tok_text = " ".join(tok_text.split())
orig_text = " ".join(orig_tokens)
final_text = get_final_text(tok_text, orig_text, do_lower_case)
if final_text in seen_predictions:
continue
seen_predictions[final_text] = True
else:
final_text = ""
seen_predictions[final_text] = True
nbest.append(
_NbestPrediction(
text=final_text,
start_logit=pred.start_logit,
end_logit=pred.end_logit))
# if we didn't inlude the empty option in the n-best, inlcude it
if FLAGS.version_2_with_negative:
if "" not in seen_predictions:
nbest.append(
_NbestPrediction(
text="", start_logit=null_start_logit,
end_logit=null_end_logit))
# In very rare edge cases we could have no valid predictions. So we
# just create a nonce prediction in this case to avoid failure.
if not nbest:
nbest.append(
_NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
assert len(nbest) >= 1
total_scores = []
best_non_null_entry = None
for entry in nbest:
total_scores.append(entry.start_logit + entry.end_logit)
if not best_non_null_entry:
if entry.text:
best_non_null_entry = entry
probs = _compute_softmax(total_scores)
nbest_json = []
for (i, entry) in enumerate(nbest):
output = collections.OrderedDict()
output["text"] = entry.text
output["probability"] = probs[i]
output["start_logit"] = entry.start_logit
output["end_logit"] = entry.end_logit
nbest_json.append(output)
assert len(nbest_json) >= 1
if not FLAGS.version_2_with_negative:
all_predictions[example.qas_id] = nbest_json[0]["text"]
else:
# predict "" iff the null score - the score of best non-null > threshold
score_diff = score_null - best_non_null_entry.start_logit - (
best_non_null_entry.end_logit)
scores_diff_json[example.qas_id] = score_diff
if score_diff > FLAGS.null_score_diff_threshold:
all_predictions[example.qas_id] = ""
else:
all_predictions[example.qas_id] = best_non_null_entry.text
all_nbest_json[example.qas_id] = nbest_json
with tf.gfile.GFile(output_prediction_file, "w") as writer:
writer.write(json.dumps(all_predictions, indent=4) + "\n")
with tf.gfile.GFile(output_nbest_file, "w") as writer:
writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
if FLAGS.version_2_with_negative:
with tf.gfile.GFile(output_null_log_odds_file, "w") as writer:
writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
def get_final_text(pred_text, orig_text, do_lower_case):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `orig_text` contains the span of our original text corresponding to the
# span that we predicted.
#
# However, `orig_text` may contain extra characters that we don't want in
# our prediction.
#
# For example, let's say:
# pred_text = steve smith
# orig_text = Steve Smith's
#
# We don't want to return `orig_text` because it contains the extra "'s".
#
# We don't want to return `pred_text` because it's already been normalized
# (the SQuAD eval script also does punctuation stripping/lower casing but
# our tokenizer does additional normalization like stripping accent
# characters).
#
# What we really want to return is "Steve Smith".
#
# Therefore, we have to apply a semi-complicated alignment heruistic between
# `pred_text` and `orig_text` to get a character-to-charcter alignment. This
# can fail in certain cases in which case we just return `orig_text`.
def _strip_spaces(text):
ns_chars = []
ns_to_s_map = collections.OrderedDict()
for (i, c) in enumerate(text):
if c == " ":
continue
ns_to_s_map[len(ns_chars)] = i
ns_chars.append(c)
ns_text = "".join(ns_chars)
return (ns_text, ns_to_s_map)
# We first tokenize `orig_text`, strip whitespace from the result
# and `pred_text`, and check if they are the same length. If they are
# NOT the same length, the heuristic has failed. If they are the same
# length, we assume the characters are one-to-one aligned.
tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)
tok_text = " ".join(tokenizer.tokenize(orig_text))
start_position = tok_text.find(pred_text)
if start_position == -1:
if FLAGS.verbose_logging:
tf.logging.info(
"Unable to find text: '%s' in '%s'" % (pred_text, orig_text))
return orig_text
end_position = start_position + len(pred_text) - 1
(orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
(tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
if len(orig_ns_text) != len(tok_ns_text):
if FLAGS.verbose_logging:
tf.logging.info("Length not equal after stripping spaces: '%s' vs '%s'",
orig_ns_text, tok_ns_text)
return orig_text
# We then project the characters in `pred_text` back to `orig_text` using
# the character-to-character alignment.
tok_s_to_ns_map = {}
for (i, tok_index) in six.iteritems(tok_ns_to_s_map):
tok_s_to_ns_map[tok_index] = i
orig_start_position = None
if start_position in tok_s_to_ns_map:
ns_start_position = tok_s_to_ns_map[start_position]
if ns_start_position in orig_ns_to_s_map:
orig_start_position = orig_ns_to_s_map[ns_start_position]
if orig_start_position is None:
if FLAGS.verbose_logging:
tf.logging.info("Couldn't map start position")
return orig_text
orig_end_position = None
if end_position in tok_s_to_ns_map:
ns_end_position = tok_s_to_ns_map[end_position]
if ns_end_position in orig_ns_to_s_map:
orig_end_position = orig_ns_to_s_map[ns_end_position]
if orig_end_position is None:
if FLAGS.verbose_logging:
tf.logging.info("Couldn't map end position")
return orig_text
output_text = orig_text[orig_start_position:(orig_end_position + 1)]
return output_text
def _get_best_indexes(logits, n_best_size):
"""Get the n-best logits from a list."""
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if i >= n_best_size:
break
best_indexes.append(index_and_score[i][0])
return best_indexes
def _compute_softmax(scores):
"""Compute softmax probability over raw logits."""
if not scores:
return []
max_score = None
for score in scores:
if max_score is None or score > max_score:
max_score = score
exp_scores = []
total_sum = 0.0
for score in scores:
x = math.exp(score - max_score)
exp_scores.append(x)
total_sum += x
probs = []
for score in exp_scores:
probs.append(score / total_sum)
return probs
class FeatureWriter(object):
"""Writes InputFeature to TF example file."""
def __init__(self, filename, is_training):
self.filename = filename
self.is_training = is_training
self.num_features = 0
self._writer = tf.python_io.TFRecordWriter(filename)
def process_feature(self, feature):
"""Write a InputFeature to the TFRecordWriter as a tf.train.Example."""
self.num_features += 1
def create_int_feature(values):
feature = tf.train.Feature(
int64_list=tf.train.Int64List(value=list(values)))
return feature
features = collections.OrderedDict()
features["unique_ids"] = create_int_feature([feature.unique_id])
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
if self.is_training:
features["start_positions"] = create_int_feature([feature.start_position])
features["end_positions"] = create_int_feature([feature.end_position])
impossible = 0
if feature.is_impossible:
impossible = 1
features["is_impossible"] = create_int_feature([impossible])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
self._writer.write(tf_example.SerializeToString())
def close(self):
self._writer.close()
def validate_flags_or_throw(bert_config):
"""Validate the input FLAGS or throw an exception."""
tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,
FLAGS.init_checkpoint)
if not FLAGS.do_train and not FLAGS.do_predict:
raise ValueError("At least one of `do_train` or `do_predict` must be True.")
if FLAGS.do_train:
if not FLAGS.train_file:
raise ValueError(
"If `do_train` is True, then `train_file` must be specified.")
if FLAGS.do_predict:
if not FLAGS.predict_file:
raise ValueError(
"If `do_predict` is True, then `predict_file` must be specified.")
if FLAGS.max_seq_length > bert_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, bert_config.max_position_embeddings))
if FLAGS.max_seq_length <= FLAGS.max_query_length + 3:
raise ValueError(
"The max_seq_length (%d) must be greater than max_query_length "
"(%d) + 3" % (FLAGS.max_seq_length, FLAGS.max_query_length))
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
validate_flags_or_throw(bert_config)
tf.gfile.MakeDirs(FLAGS.output_dir)
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = read_squad_examples(
input_file=FLAGS.train_file, is_training=True)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
# Pre-shuffle the input to avoid having to make a very large shuffle
# buffer in in the `input_fn`.
rng = random.Random(12345)
rng.shuffle(train_examples)
model_fn = model_fn_builder(
bert_config=bert_config,
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
# We write to a temporary file to avoid storing very large constant tensors
# in memory.
train_writer = FeatureWriter(
filename=os.path.join(FLAGS.output_dir, "train.tf_record"),
is_training=True)
convert_examples_to_features(
examples=train_examples,
tokenizer=tokenizer,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=True,
output_fn=train_writer.process_feature)
train_writer.close()
tf.logging.info("***** Running training *****")
tf.logging.info(" Num orig examples = %d", len(train_examples))
tf.logging.info(" Num split examples = %d", train_writer.num_features)
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
del train_examples
train_input_fn = input_fn_builder(
input_file=train_writer.filename,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_predict:
eval_examples = read_squad_examples(
input_file=FLAGS.predict_file, is_training=False)
eval_writer = FeatureWriter(
filename=os.path.join(FLAGS.output_dir, "eval.tf_record"),
is_training=False)
eval_features = []
def append_feature(feature):
eval_features.append(feature)
eval_writer.process_feature(feature)
convert_examples_to_features(
examples=eval_examples,
tokenizer=tokenizer,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=False,
output_fn=append_feature)
eval_writer.close()
tf.logging.info("***** Running predictions *****")
tf.logging.info(" Num orig examples = %d", len(eval_examples))
tf.logging.info(" Num split examples = %d", len(eval_features))
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
all_results = []
predict_input_fn = input_fn_builder(
input_file=eval_writer.filename,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=False)
# If running eval on the TPU, you will need to specify the number of
# steps.
all_results = []
for result in estimator.predict(
predict_input_fn, yield_single_examples=True):
if len(all_results) % 1000 == 0:
tf.logging.info("Processing example: %d" % (len(all_results)))
unique_id = int(result["unique_ids"])
start_logits = [float(x) for x in result["start_logits"].flat]
end_logits = [float(x) for x in result["end_logits"].flat]
all_results.append(
RawResult(
unique_id=unique_id,
start_logits=start_logits,
end_logits=end_logits))
output_prediction_file = os.path.join(FLAGS.output_dir, "predictions.json")
output_nbest_file = os.path.join(FLAGS.output_dir, "nbest_predictions.json")
output_null_log_odds_file = os.path.join(FLAGS.output_dir, "null_odds.json")
write_predictions(eval_examples, eval_features, all_results,
FLAGS.n_best_size, FLAGS.max_answer_length,
FLAGS.do_lower_case, output_prediction_file,
output_nbest_file, output_null_log_odds_file)
if __name__ == "__main__":
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| 46,532 | 35.240654 | 82 | py |
CLUE | CLUE-master/baselines/models/ernie/run_classifier.py | # -*- coding: utf-8 -*-
# @Author: bo.shi
# @Date: 2019-11-04 09:56:36
# @Last Modified by: bo.shi
# @Last Modified time: 2019-12-04 14:30:20
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BERT finetuning runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import modeling
import optimization
import tokenization
import tensorflow as tf
import sys
sys.path.append('..')
from classifier_utils import *
flags = tf.flags
FLAGS = flags.FLAGS
# Required parameters
flags.DEFINE_string(
"data_dir", None,
"The input data dir. Should contain the .tsv files (or other data files) "
"for the task.")
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_string("task_name", None, "The name of the task to train.")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written.")
# Other parameters
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_integer(
"max_seq_length", 128,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded.")
flags.DEFINE_bool("do_train", False, "Whether to run training.")
flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
flags.DEFINE_bool(
"do_predict", False,
"Whether to run the model in inference mode on the test set.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predict.")
flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
flags.DEFINE_float("num_train_epochs", 3.0,
"Total number of training epochs to perform.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
tf.flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
tf.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
input_ids,
input_mask,
segment_ids,
label_id,
is_real_example=True):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
self.is_real_example = is_real_example
def convert_single_example_for_inews(ex_index, tokens_a, tokens_b, label_map, max_seq_length,
tokenizer, example):
if tokens_b:
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for [CLS], [SEP], [SEP] with "- 3"
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
else:
# Account for [CLS] and [SEP] with "- 2"
if len(tokens_a) > max_seq_length - 2:
tokens_a = tokens_a[0:(max_seq_length - 2)]
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens = []
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in tokens_a:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
if tokens_b:
for token in tokens_b:
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
label_id = label_map[example.label]
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id,
is_real_example=True)
return feature
def convert_example_list_for_inews(ex_index, example, label_list, max_seq_length,
tokenizer):
"""Converts a single `InputExample` into a single `InputFeatures`."""
if isinstance(example, PaddingInputExample):
return [InputFeatures(
input_ids=[0] * max_seq_length,
input_mask=[0] * max_seq_length,
segment_ids=[0] * max_seq_length,
label_id=0,
is_real_example=False)]
label_map = {}
for (i, label) in enumerate(label_list):
label_map[label] = i
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
must_len = len(tokens_a) + 3
extra_len = max_seq_length - must_len
feature_list = []
if example.text_b and extra_len > 0:
extra_num = int((len(tokens_b) - 1) / extra_len) + 1
for num in range(extra_num):
max_len = min((num + 1) * extra_len, len(tokens_b))
tokens_b_sub = tokens_b[num * extra_len: max_len]
feature = convert_single_example_for_inews(
ex_index, tokens_a, tokens_b_sub, label_map, max_seq_length, tokenizer, example)
feature_list.append(feature)
else:
feature = convert_single_example_for_inews(
ex_index, tokens_a, tokens_b, label_map, max_seq_length, tokenizer, example)
feature_list.append(feature)
return feature_list
def file_based_convert_examples_to_features_for_inews(
examples, label_list, max_seq_length, tokenizer, output_file):
"""Convert a set of `InputExample`s to a TFRecord file."""
writer = tf.python_io.TFRecordWriter(output_file)
num_example = 0
for (ex_index, example) in enumerate(examples):
if ex_index % 1000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature_list = convert_example_list_for_inews(ex_index, example, label_list,
max_seq_length, tokenizer)
num_example += len(feature_list)
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
features = collections.OrderedDict()
for feature in feature_list:
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["label_ids"] = create_int_feature([feature.label_id])
features["is_real_example"] = create_int_feature(
[int(feature.is_real_example)])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
tf.logging.info("feature num: %s", num_example)
writer.close()
def convert_single_example(ex_index, example, label_list, max_seq_length,
tokenizer):
"""Converts a single `InputExample` into a single `InputFeatures`."""
if isinstance(example, PaddingInputExample):
return InputFeatures(
input_ids=[0] * max_seq_length,
input_mask=[0] * max_seq_length,
segment_ids=[0] * max_seq_length,
label_id=0,
is_real_example=False)
label_map = {}
for (i, label) in enumerate(label_list):
label_map[label] = i
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
if tokens_b:
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for [CLS], [SEP], [SEP] with "- 3"
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
else:
# Account for [CLS] and [SEP] with "- 2"
if len(tokens_a) > max_seq_length - 2:
tokens_a = tokens_a[0:(max_seq_length - 2)]
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens = []
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in tokens_a:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
if tokens_b:
for token in tokens_b:
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
label_id = label_map[example.label]
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id,
is_real_example=True)
return feature
def file_based_convert_examples_to_features(
examples, label_list, max_seq_length, tokenizer, output_file):
"""Convert a set of `InputExample`s to a TFRecord file."""
writer = tf.python_io.TFRecordWriter(output_file)
for (ex_index, example) in enumerate(examples):
if ex_index % 10000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature = convert_single_example(ex_index, example, label_list,
max_seq_length, tokenizer)
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
features = collections.OrderedDict()
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["label_ids"] = create_int_feature([feature.label_id])
features["is_real_example"] = create_int_feature(
[int(feature.is_real_example)])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
writer.close()
def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([], tf.int64),
"is_real_example": tf.FixedLenFeature([], tf.int64),
}
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder))
return d
return input_fn
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
labels, num_labels, use_one_hot_embeddings):
"""Creates a classification model."""
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
# In the demo, we are doing a simple classification task on the entire
# segment.
#
# If you want to use the token-level output, use model.get_sequence_output()
# instead.
output_layer = model.get_pooled_output()
hidden_size = output_layer.shape[-1].value
output_weights = tf.get_variable(
"output_weights", [num_labels, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer())
with tf.variable_scope("loss"):
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax(logits, axis=-1)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, logits, probabilities)
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]
is_real_example = None
if "is_real_example" in features:
is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32)
else:
is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(total_loss, per_example_loss, logits, probabilities) = create_model(
bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,
num_labels, use_one_hot_embeddings)
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits, is_real_example):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
accuracy = tf.metrics.accuracy(
labels=label_ids, predictions=predictions, weights=is_real_example)
loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
return {
"eval_accuracy": accuracy,
"eval_loss": loss,
}
eval_metrics = (metric_fn,
[per_example_loss, label_ids, logits, is_real_example])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
predictions={"probabilities": probabilities},
scaffold_fn=scaffold_fn)
return output_spec
return model_fn
# This function is not used by this file but is still used by the Colab and
# people who depend on it.
def input_fn_builder(features, seq_length, is_training, drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
all_input_ids = []
all_input_mask = []
all_segment_ids = []
all_label_ids = []
for feature in features:
all_input_ids.append(feature.input_ids)
all_input_mask.append(feature.input_mask)
all_segment_ids.append(feature.segment_ids)
all_label_ids.append(feature.label_id)
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
num_examples = len(features)
# This is for demo purposes and does NOT scale to large data sets. We do
# not use Dataset.from_generator() because that uses tf.py_func which is
# not TPU compatible. The right way to load data is with TFRecordReader.
d = tf.data.Dataset.from_tensor_slices({
"input_ids":
tf.constant(
all_input_ids, shape=[num_examples, seq_length],
dtype=tf.int32),
"input_mask":
tf.constant(
all_input_mask,
shape=[num_examples, seq_length],
dtype=tf.int32),
"segment_ids":
tf.constant(
all_segment_ids,
shape=[num_examples, seq_length],
dtype=tf.int32),
"label_ids":
tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),
})
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)
return d
return input_fn
# This function is not used by this file but is still used by the Colab and
# people who depend on it.
def convert_examples_to_features(examples, label_list, max_seq_length,
tokenizer):
"""Convert a set of `InputExample`s to a list of `InputFeatures`."""
features = []
for (ex_index, example) in enumerate(examples):
if ex_index % 10000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature = convert_single_example(ex_index, example, label_list,
max_seq_length, tokenizer)
features.append(feature)
return features
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"xnli": XnliProcessor,
"tnews": TnewsProcessor,
"afqmc": AFQMCProcessor,
"iflytek": iFLYTEKDataProcessor,
"copa": COPAProcessor,
"cmnli": CMNLIProcessor,
"wsc": WSCProcessor,
"csl": CslProcessor,
"copa": COPAProcessor,
}
tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,
FLAGS.init_checkpoint)
if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:
raise ValueError(
"At least one of `do_train`, `do_eval` or `do_predict' must be True.")
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
if FLAGS.max_seq_length > bert_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, bert_config.max_position_embeddings))
tf.gfile.MakeDirs(FLAGS.output_dir)
task_name = FLAGS.task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
label_list = processor.get_labels()
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = processor.get_train_examples(FLAGS.data_dir)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
model_fn = model_fn_builder(
bert_config=bert_config,
num_labels=len(label_list),
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
if task_name == "inews":
file_based_convert_examples_to_features_for_inews(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
else:
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = file_based_input_fn_builder(
input_file=train_file,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_eval:
# dev dataset
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
num_actual_eval_examples = len(eval_examples)
if FLAGS.use_tpu:
# TPU requires a fixed batch size for all batches, therefore the number
# of examples must be a multiple of the batch size, or else examples
# will get dropped. So we pad with fake examples which are ignored
# later on. These do NOT count towards the metric (all tf.metrics
# support a per-instance weight, and these get a weight of 0.0).
while len(eval_examples) % FLAGS.eval_batch_size != 0:
eval_examples.append(PaddingInputExample())
eval_file = os.path.join(FLAGS.output_dir, "dev.tf_record")
if task_name == "inews":
file_based_convert_examples_to_features_for_inews(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
else:
file_based_convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
len(eval_examples), num_actual_eval_examples,
len(eval_examples) - num_actual_eval_examples)
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
# This tells the estimator to run through the entire set.
eval_steps = None
# However, if running eval on the TPU, you will need to specify the
# number of steps.
if FLAGS.use_tpu:
assert len(eval_examples) % FLAGS.eval_batch_size == 0
eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)
eval_drop_remainder = True if FLAGS.use_tpu else False
eval_input_fn = file_based_input_fn_builder(
input_file=eval_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=eval_drop_remainder)
#######################################################################################################################
# evaluate all checkpoints; you can use the checkpoint with the best dev accuarcy
steps_and_files = []
filenames = tf.gfile.ListDirectory(FLAGS.output_dir)
for filename in filenames:
if filename.endswith(".index"):
ckpt_name = filename[:-6]
cur_filename = os.path.join(FLAGS.output_dir, ckpt_name)
global_step = int(cur_filename.split("-")[-1])
tf.logging.info("Add {} to eval list.".format(cur_filename))
steps_and_files.append([global_step, cur_filename])
steps_and_files = sorted(steps_and_files, key=lambda x: x[0])
output_eval_file = os.path.join(FLAGS.data_dir, "dev_results_ernie.txt")
print("output_eval_file:", output_eval_file)
tf.logging.info("output_eval_file:" + output_eval_file)
with tf.gfile.GFile(output_eval_file, "w") as writer:
for global_step, filename in sorted(steps_and_files, key=lambda x: x[0]):
result = estimator.evaluate(input_fn=eval_input_fn,
steps=eval_steps, checkpoint_path=filename)
tf.logging.info("***** Eval results %s *****" % (filename))
writer.write("***** Eval results %s *****\n" % (filename))
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
#######################################################################################################################
# result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
#
# output_eval_file = os.path.join(FLAGS.output_dir, "dev_results_ernie.txt")
# with tf.gfile.GFile(output_eval_file, "w") as writer:
# tf.logging.info("***** Eval results *****")
# for key in sorted(result.keys()):
# tf.logging.info(" %s = %s", key, str(result[key]))
# writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_predict:
predict_examples = processor.get_test_examples(FLAGS.data_dir)
num_actual_predict_examples = len(predict_examples)
if FLAGS.use_tpu:
# TPU requires a fixed batch size for all batches, therefore the number
# of examples must be a multiple of the batch size, or else examples
# will get dropped. So we pad with fake examples which are ignored
# later on.
while len(predict_examples) % FLAGS.predict_batch_size != 0:
predict_examples.append(PaddingInputExample())
predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
if task_name == "inews":
file_based_convert_examples_to_features_for_inews(predict_examples, label_list,
FLAGS.max_seq_length, tokenizer,
predict_file)
else:
file_based_convert_examples_to_features(predict_examples, label_list,
FLAGS.max_seq_length, tokenizer,
predict_file)
tf.logging.info("***** Running prediction*****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
len(predict_examples), num_actual_predict_examples,
len(predict_examples) - num_actual_predict_examples)
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
predict_drop_remainder = True if FLAGS.use_tpu else False
predict_input_fn = file_based_input_fn_builder(
input_file=predict_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=predict_drop_remainder)
result = estimator.predict(input_fn=predict_input_fn)
index2label_map = {}
for (i, label) in enumerate(label_list):
index2label_map[i] = label
output_predict_file_label_name = task_name + "_predict.json"
output_predict_file_label = os.path.join(FLAGS.output_dir, output_predict_file_label_name)
output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
with tf.gfile.GFile(output_predict_file_label, "w") as writer_label:
with tf.gfile.GFile(output_predict_file, "w") as writer:
num_written_lines = 0
tf.logging.info("***** Predict results *****")
for (i, prediction) in enumerate(result):
probabilities = prediction["probabilities"]
label_index = probabilities.argmax(0)
if i >= num_actual_predict_examples:
break
output_line = "\t".join(
str(class_probability)
for class_probability in probabilities) + "\n"
test_label_dict = {}
test_label_dict["id"] = i
test_label_dict["label"] = str(index2label_map[label_index])
if task_name == "tnews":
test_label_dict["label_desc"] = ""
writer.write(output_line)
json.dump(test_label_dict, writer_label)
writer_label.write("\n")
num_written_lines += 1
assert num_written_lines == num_actual_predict_examples
if __name__ == "__main__":
flags.mark_flag_as_required("data_dir")
flags.mark_flag_as_required("task_name")
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| 36,142 | 36.299278 | 123 | py |
CLUE | CLUE-master/baselines/models/ernie/tf_metrics.py | """
Multiclass
from:
https://github.com/guillaumegenthial/tf_metrics/blob/master/tf_metrics/__init__.py
"""
__author__ = "Guillaume Genthial"
import numpy as np
import tensorflow as tf
from tensorflow.python.ops.metrics_impl import _streaming_confusion_matrix
def precision(labels, predictions, num_classes, pos_indices=None,
weights=None, average='micro'):
"""Multi-class precision metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, optional
The indices of the positive classes, default is all
weights : Tensor of tf.int32, optional
Mask, must be of compatible shape with labels
average : str, optional
'micro': counts the total number of true positives, false
positives, and false negatives for the classes in
`pos_indices` and infer the metric from it.
'macro': will compute the metric separately for each class in
`pos_indices` and average. Will not account for class
imbalance.
'weighted': will compute the metric separately for each class in
`pos_indices` and perform a weighted average by the total
number of true labels for each class.
Returns
-------
tuple of (scalar float Tensor, update_op)
"""
cm, op = _streaming_confusion_matrix(
labels, predictions, num_classes, weights)
pr, _, _ = metrics_from_confusion_matrix(
cm, pos_indices, average=average)
op, _, _ = metrics_from_confusion_matrix(
op, pos_indices, average=average)
return (pr, op)
def recall(labels, predictions, num_classes, pos_indices=None, weights=None,
average='micro'):
"""Multi-class recall metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, optional
The indices of the positive classes, default is all
weights : Tensor of tf.int32, optional
Mask, must be of compatible shape with labels
average : str, optional
'micro': counts the total number of true positives, false
positives, and false negatives for the classes in
`pos_indices` and infer the metric from it.
'macro': will compute the metric separately for each class in
`pos_indices` and average. Will not account for class
imbalance.
'weighted': will compute the metric separately for each class in
`pos_indices` and perform a weighted average by the total
number of true labels for each class.
Returns
-------
tuple of (scalar float Tensor, update_op)
"""
cm, op = _streaming_confusion_matrix(
labels, predictions, num_classes, weights)
_, re, _ = metrics_from_confusion_matrix(
cm, pos_indices, average=average)
_, op, _ = metrics_from_confusion_matrix(
op, pos_indices, average=average)
return (re, op)
def f1(labels, predictions, num_classes, pos_indices=None, weights=None,
average='micro'):
return fbeta(labels, predictions, num_classes, pos_indices, weights,
average)
def fbeta(labels, predictions, num_classes, pos_indices=None, weights=None,
average='micro', beta=1):
"""Multi-class fbeta metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, optional
The indices of the positive classes, default is all
weights : Tensor of tf.int32, optional
Mask, must be of compatible shape with labels
average : str, optional
'micro': counts the total number of true positives, false
positives, and false negatives for the classes in
`pos_indices` and infer the metric from it.
'macro': will compute the metric separately for each class in
`pos_indices` and average. Will not account for class
imbalance.
'weighted': will compute the metric separately for each class in
`pos_indices` and perform a weighted average by the total
number of true labels for each class.
beta : int, optional
Weight of precision in harmonic mean
Returns
-------
tuple of (scalar float Tensor, update_op)
"""
cm, op = _streaming_confusion_matrix(
labels, predictions, num_classes, weights)
_, _, fbeta = metrics_from_confusion_matrix(
cm, pos_indices, average=average, beta=beta)
_, _, op = metrics_from_confusion_matrix(
op, pos_indices, average=average, beta=beta)
return (fbeta, op)
def safe_div(numerator, denominator):
"""Safe division, return 0 if denominator is 0"""
numerator, denominator = tf.to_float(numerator), tf.to_float(denominator)
zeros = tf.zeros_like(numerator, dtype=numerator.dtype)
denominator_is_zero = tf.equal(denominator, zeros)
return tf.where(denominator_is_zero, zeros, numerator / denominator)
def pr_re_fbeta(cm, pos_indices, beta=1):
"""Uses a confusion matrix to compute precision, recall and fbeta"""
num_classes = cm.shape[0]
neg_indices = [i for i in range(num_classes) if i not in pos_indices]
cm_mask = np.ones([num_classes, num_classes])
cm_mask[neg_indices, neg_indices] = 0
diag_sum = tf.reduce_sum(tf.diag_part(cm * cm_mask))
cm_mask = np.ones([num_classes, num_classes])
cm_mask[:, neg_indices] = 0
tot_pred = tf.reduce_sum(cm * cm_mask)
cm_mask = np.ones([num_classes, num_classes])
cm_mask[neg_indices, :] = 0
tot_gold = tf.reduce_sum(cm * cm_mask)
pr = safe_div(diag_sum, tot_pred)
re = safe_div(diag_sum, tot_gold)
fbeta = safe_div((1. + beta**2) * pr * re, beta**2 * pr + re)
return pr, re, fbeta
def metrics_from_confusion_matrix(cm, pos_indices=None, average='micro',
beta=1):
"""Precision, Recall and F1 from the confusion matrix
Parameters
----------
cm : tf.Tensor of type tf.int32, of shape (num_classes, num_classes)
The streaming confusion matrix.
pos_indices : list of int, optional
The indices of the positive classes
beta : int, optional
Weight of precision in harmonic mean
average : str, optional
'micro', 'macro' or 'weighted'
"""
num_classes = cm.shape[0]
if pos_indices is None:
pos_indices = [i for i in range(num_classes)]
if average == 'micro':
return pr_re_fbeta(cm, pos_indices, beta)
elif average in {'macro', 'weighted'}:
precisions, recalls, fbetas, n_golds = [], [], [], []
for idx in pos_indices:
pr, re, fbeta = pr_re_fbeta(cm, [idx], beta)
precisions.append(pr)
recalls.append(re)
fbetas.append(fbeta)
cm_mask = np.zeros([num_classes, num_classes])
cm_mask[idx, :] = 1
n_golds.append(tf.to_float(tf.reduce_sum(cm * cm_mask)))
if average == 'macro':
pr = tf.reduce_mean(precisions)
re = tf.reduce_mean(recalls)
fbeta = tf.reduce_mean(fbetas)
return pr, re, fbeta
if average == 'weighted':
n_gold = tf.reduce_sum(n_golds)
pr_sum = sum(p * n for p, n in zip(precisions, n_golds))
pr = safe_div(pr_sum, n_gold)
re_sum = sum(r * n for r, n in zip(recalls, n_golds))
re = safe_div(re_sum, n_gold)
fbeta_sum = sum(f * n for f, n in zip(fbetas, n_golds))
fbeta = safe_div(fbeta_sum, n_gold)
return pr, re, fbeta
else:
raise NotImplementedError() | 8,188 | 37.088372 | 82 | py |
CLUE | CLUE-master/baselines/models/ernie/tokenization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tokenization classes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import re
import unicodedata
import six
import tensorflow as tf
def validate_case_matches_checkpoint(do_lower_case, init_checkpoint):
"""Checks whether the casing config is consistent with the checkpoint name."""
# The casing has to be passed in by the user and there is no explicit check
# as to whether it matches the checkpoint. The casing information probably
# should have been stored in the bert_config.json file, but it's not, so
# we have to heuristically detect it to validate.
if not init_checkpoint:
return
m = re.match("^.*?([A-Za-z0-9_-]+)/bert_model.ckpt", init_checkpoint)
if m is None:
return
model_name = m.group(1)
lower_models = [
"uncased_L-24_H-1024_A-16", "uncased_L-12_H-768_A-12",
"multilingual_L-12_H-768_A-12", "chinese_L-12_H-768_A-12"
]
cased_models = [
"cased_L-12_H-768_A-12", "cased_L-24_H-1024_A-16",
"multi_cased_L-12_H-768_A-12"
]
is_bad_config = False
if model_name in lower_models and not do_lower_case:
is_bad_config = True
actual_flag = "False"
case_name = "lowercased"
opposite_flag = "True"
if model_name in cased_models and do_lower_case:
is_bad_config = True
actual_flag = "True"
case_name = "cased"
opposite_flag = "False"
if is_bad_config:
raise ValueError(
"You passed in `--do_lower_case=%s` with `--init_checkpoint=%s`. "
"However, `%s` seems to be a %s model, so you "
"should pass in `--do_lower_case=%s` so that the fine-tuning matches "
"how the model was pre-training. If this error is wrong, please "
"just comment out this check." % (actual_flag, init_checkpoint,
model_name, case_name, opposite_flag))
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text.decode("utf-8", "ignore")
elif isinstance(text, unicode):
return text
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?")
def printable_text(text):
"""Returns text encoded in a way suitable for print or `tf.logging`."""
# These functions want `str` for both Python2 and Python3, but in one case
# it's a Unicode string and in the other it's a byte string.
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text
elif isinstance(text, unicode):
return text.encode("utf-8")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?")
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
index = 0
with tf.gfile.GFile(vocab_file, "r") as reader:
while True:
token = convert_to_unicode(reader.readline())
if not token:
break
token = token.strip()
vocab[token] = index
index += 1
return vocab
def convert_by_vocab(vocab, items):
"""Converts a sequence of [tokens|ids] using the vocab."""
output = []
for item in items:
output.append(vocab[item])
return output
def convert_tokens_to_ids(vocab, tokens):
return convert_by_vocab(vocab, tokens)
def convert_ids_to_tokens(inv_vocab, ids):
return convert_by_vocab(inv_vocab, ids)
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens
class FullTokenizer(object):
"""Runs end-to-end tokenziation."""
def __init__(self, vocab_file, do_lower_case=True):
self.vocab = load_vocab(vocab_file)
self.inv_vocab = {v: k for k, v in self.vocab.items()}
self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
def tokenize(self, text):
split_tokens = []
for token in self.basic_tokenizer.tokenize(text):
for sub_token in self.wordpiece_tokenizer.tokenize(token):
split_tokens.append(sub_token)
return split_tokens
def convert_tokens_to_ids(self, tokens):
return convert_by_vocab(self.vocab, tokens)
def convert_ids_to_tokens(self, ids):
return convert_by_vocab(self.inv_vocab, ids)
class BasicTokenizer(object):
"""Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
def __init__(self, do_lower_case=True):
"""Constructs a BasicTokenizer.
Args:
do_lower_case: Whether to lower case the input.
"""
self.do_lower_case = do_lower_case
def tokenize(self, text):
"""Tokenizes a piece of text."""
text = convert_to_unicode(text)
text = self._clean_text(text)
# This was added on November 1st, 2018 for the multilingual and Chinese
# models. This is also applied to the English models now, but it doesn't
# matter since the English models were not trained on any Chinese data
# and generally don't have any Chinese data in them (there are Chinese
# characters in the vocabulary because Wikipedia does have some Chinese
# words in the English Wikipedia.).
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if self.do_lower_case:
token = token.lower()
token = self._run_strip_accents(token)
split_tokens.extend(self._run_split_on_punc(token))
output_tokens = whitespace_tokenize(" ".join(split_tokens))
return output_tokens
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output)
def _run_split_on_punc(self, text):
"""Splits punctuation on a piece of text."""
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return ["".join(x) for x in output]
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output)
def _is_chinese_char(self, cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
(cp >= 0x3400 and cp <= 0x4DBF) or #
(cp >= 0x20000 and cp <= 0x2A6DF) or #
(cp >= 0x2A700 and cp <= 0x2B73F) or #
(cp >= 0x2B740 and cp <= 0x2B81F) or #
(cp >= 0x2B820 and cp <= 0x2CEAF) or
(cp >= 0xF900 and cp <= 0xFAFF) or #
(cp >= 0x2F800 and cp <= 0x2FA1F)): #
return True
return False
def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp == 0 or cp == 0xfffd or _is_control(char):
continue
if _is_whitespace(char):
output.append(" ")
else:
output.append(char)
return "".join(output)
class WordpieceTokenizer(object):
"""Runs WordPiece tokenziation."""
def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=200):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through `BasicTokenizer.
Returns:
A list of wordpiece tokens.
"""
text = convert_to_unicode(text)
output_tokens = []
for token in whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens
def _is_whitespace(char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
cat = unicodedata.category(char)
if cat == "Zs":
return True
return False
def _is_control(char):
"""Checks whether `chars` is a control character."""
# These are technically control characters but we count them as whitespace
# characters.
if char == "\t" or char == "\n" or char == "\r":
return False
cat = unicodedata.category(char)
if cat in ("Cc", "Cf"):
return True
return False
def _is_punctuation(char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, for
# consistency.
if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
(cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
return True
cat = unicodedata.category(char)
if cat.startswith("P"):
return True
return False
| 12,257 | 29.645 | 80 | py |
CLUE | CLUE-master/baselines/models/ernie/modeling.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The main BERT model and related functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import json
import math
import re
import numpy as np
import six
import tensorflow as tf
class BertConfig(object):
"""Configuration for `BertModel`."""
def __init__(self,
vocab_size,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=16,
initializer_range=0.02):
"""Constructs BertConfig.
Args:
vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.
hidden_size: Size of the encoder layers and the pooler layer.
num_hidden_layers: Number of hidden layers in the Transformer encoder.
num_attention_heads: Number of attention heads for each attention layer in
the Transformer encoder.
intermediate_size: The size of the "intermediate" (i.e., feed-forward)
layer in the Transformer encoder.
hidden_act: The non-linear activation function (function or string) in the
encoder and pooler.
hidden_dropout_prob: The dropout probability for all fully connected
layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob: The dropout ratio for the attention
probabilities.
max_position_embeddings: The maximum sequence length that this model might
ever be used with. Typically set this to something large just in case
(e.g., 512 or 1024 or 2048).
type_vocab_size: The vocabulary size of the `token_type_ids` passed into
`BertModel`.
initializer_range: The stdev of the truncated_normal_initializer for
initializing all weight matrices.
"""
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
@classmethod
def from_dict(cls, json_object):
"""Constructs a `BertConfig` from a Python dictionary of parameters."""
config = BertConfig(vocab_size=None)
for (key, value) in six.iteritems(json_object):
config.__dict__[key] = value
return config
@classmethod
def from_json_file(cls, json_file):
"""Constructs a `BertConfig` from a json file of parameters."""
with tf.gfile.GFile(json_file, "r") as reader:
text = reader.read()
return cls.from_dict(json.loads(text))
def to_dict(self):
"""Serializes this instance to a Python dictionary."""
output = copy.deepcopy(self.__dict__)
return output
def to_json_string(self):
"""Serializes this instance to a JSON string."""
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
class BertModel(object):
"""BERT model ("Bidirectional Encoder Representations from Transformers").
Example usage:
```python
# Already been converted into WordPiece token ids
input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])
input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])
token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]])
config = modeling.BertConfig(vocab_size=32000, hidden_size=512,
num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)
model = modeling.BertModel(config=config, is_training=True,
input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)
label_embeddings = tf.get_variable(...)
pooled_output = model.get_pooled_output()
logits = tf.matmul(pooled_output, label_embeddings)
...
```
"""
def __init__(self,
config,
is_training,
input_ids,
input_mask=None,
token_type_ids=None,
use_one_hot_embeddings=False,
scope=None):
"""Constructor for BertModel.
Args:
config: `BertConfig` instance.
is_training: bool. true for training model, false for eval model. Controls
whether dropout will be applied.
input_ids: int32 Tensor of shape [batch_size, seq_length].
input_mask: (optional) int32 Tensor of shape [batch_size, seq_length].
token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
use_one_hot_embeddings: (optional) bool. Whether to use one-hot word
embeddings or tf.embedding_lookup() for the word embeddings.
scope: (optional) variable scope. Defaults to "bert".
Raises:
ValueError: The config is invalid or one of the input tensor shapes
is invalid.
"""
config = copy.deepcopy(config)
if not is_training:
config.hidden_dropout_prob = 0.0
config.attention_probs_dropout_prob = 0.0
input_shape = get_shape_list(input_ids, expected_rank=2)
batch_size = input_shape[0]
seq_length = input_shape[1]
if input_mask is None:
input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)
if token_type_ids is None:
token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)
with tf.variable_scope(scope, default_name="bert"):
with tf.variable_scope("embeddings"):
# Perform embedding lookup on the word ids.
(self.embedding_output, self.embedding_table) = embedding_lookup(
input_ids=input_ids,
vocab_size=config.vocab_size,
embedding_size=config.hidden_size,
initializer_range=config.initializer_range,
word_embedding_name="word_embeddings",
use_one_hot_embeddings=use_one_hot_embeddings)
# Add positional embeddings and token type embeddings, then layer
# normalize and perform dropout.
self.embedding_output = embedding_postprocessor(
input_tensor=self.embedding_output,
use_token_type=True,
token_type_ids=token_type_ids,
token_type_vocab_size=config.type_vocab_size,
token_type_embedding_name="token_type_embeddings",
use_position_embeddings=True,
position_embedding_name="position_embeddings",
initializer_range=config.initializer_range,
max_position_embeddings=config.max_position_embeddings,
dropout_prob=config.hidden_dropout_prob)
with tf.variable_scope("encoder"):
# This converts a 2D mask of shape [batch_size, seq_length] to a 3D
# mask of shape [batch_size, seq_length, seq_length] which is used
# for the attention scores.
attention_mask = create_attention_mask_from_input_mask(
input_ids, input_mask)
# Run the stacked transformer.
# `sequence_output` shape = [batch_size, seq_length, hidden_size].
self.all_encoder_layers = transformer_model(
input_tensor=self.embedding_output,
attention_mask=attention_mask,
hidden_size=config.hidden_size,
num_hidden_layers=config.num_hidden_layers,
num_attention_heads=config.num_attention_heads,
intermediate_size=config.intermediate_size,
intermediate_act_fn=get_activation(config.hidden_act),
hidden_dropout_prob=config.hidden_dropout_prob,
attention_probs_dropout_prob=config.attention_probs_dropout_prob,
initializer_range=config.initializer_range,
do_return_all_layers=True)
self.sequence_output = self.all_encoder_layers[-1]
# The "pooler" converts the encoded sequence tensor of shape
# [batch_size, seq_length, hidden_size] to a tensor of shape
# [batch_size, hidden_size]. This is necessary for segment-level
# (or segment-pair-level) classification tasks where we need a fixed
# dimensional representation of the segment.
with tf.variable_scope("pooler"):
# We "pool" the model by simply taking the hidden state corresponding
# to the first token. We assume that this has been pre-trained
first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)
self.pooled_output = tf.layers.dense(
first_token_tensor,
config.hidden_size,
activation=tf.tanh,
kernel_initializer=create_initializer(config.initializer_range))
def get_pooled_output(self):
return self.pooled_output
def get_sequence_output(self):
"""Gets final hidden layer of encoder.
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size] corresponding
to the final hidden of the transformer encoder.
"""
return self.sequence_output
def get_all_encoder_layers(self):
return self.all_encoder_layers
def get_embedding_output(self):
"""Gets output of the embedding lookup (i.e., input to the transformer).
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size] corresponding
to the output of the embedding layer, after summing the word
embeddings with the positional embeddings and the token type embeddings,
then performing layer normalization. This is the input to the transformer.
"""
return self.embedding_output
def get_embedding_table(self):
return self.embedding_table
def gelu(x):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
`x` with the GELU activation applied.
"""
cdf = 0.5 * (1.0 + tf.tanh(
(np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
return x * cdf
def get_activation(activation_string):
"""Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
Args:
activation_string: String name of the activation function.
Returns:
A Python function corresponding to the activation function. If
`activation_string` is None, empty, or "linear", this will return None.
If `activation_string` is not a string, it will return `activation_string`.
Raises:
ValueError: The `activation_string` does not correspond to a known
activation.
"""
# We assume that anything that"s not a string is already an activation
# function, so we just return it.
if not isinstance(activation_string, six.string_types):
return activation_string
if not activation_string:
return None
act = activation_string.lower()
if act == "linear":
return None
elif act == "relu":
return tf.nn.relu
elif act == "gelu":
return gelu
elif act == "tanh":
return tf.tanh
else:
raise ValueError("Unsupported activation: %s" % act)
def get_assignment_map_from_checkpoint(tvars, init_checkpoint):
"""Compute the union of the current variables and checkpoint variables."""
assignment_map = {}
initialized_variable_names = {}
name_to_variable = collections.OrderedDict()
for var in tvars:
name = var.name
m = re.match("^(.*):\\d+$", name)
if m is not None:
name = m.group(1)
name_to_variable[name] = var
init_vars = tf.train.list_variables(init_checkpoint)
assignment_map = collections.OrderedDict()
for x in init_vars:
(name, var) = (x[0], x[1])
if name not in name_to_variable:
continue
assignment_map[name] = name
initialized_variable_names[name] = 1
initialized_variable_names[name + ":0"] = 1
return (assignment_map, initialized_variable_names)
def dropout(input_tensor, dropout_prob):
"""Perform dropout.
Args:
input_tensor: float Tensor.
dropout_prob: Python float. The probability of dropping out a value (NOT of
*keeping* a dimension as in `tf.nn.dropout`).
Returns:
A version of `input_tensor` with dropout applied.
"""
if dropout_prob is None or dropout_prob == 0.0:
return input_tensor
output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)
return output
def layer_norm(input_tensor, name=None):
"""Run layer normalization on the last dimension of the tensor."""
return tf.contrib.layers.layer_norm(
inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
"""Runs layer normalization followed by dropout."""
output_tensor = layer_norm(input_tensor, name)
output_tensor = dropout(output_tensor, dropout_prob)
return output_tensor
def create_initializer(initializer_range=0.02):
"""Creates a `truncated_normal_initializer` with the given range."""
return tf.truncated_normal_initializer(stddev=initializer_range)
def embedding_lookup(input_ids,
vocab_size,
embedding_size=128,
initializer_range=0.02,
word_embedding_name="word_embeddings",
use_one_hot_embeddings=False):
"""Looks up words embeddings for id tensor.
Args:
input_ids: int32 Tensor of shape [batch_size, seq_length] containing word
ids.
vocab_size: int. Size of the embedding vocabulary.
embedding_size: int. Width of the word embeddings.
initializer_range: float. Embedding initialization range.
word_embedding_name: string. Name of the embedding table.
use_one_hot_embeddings: bool. If True, use one-hot method for word
embeddings. If False, use `tf.gather()`.
Returns:
float Tensor of shape [batch_size, seq_length, embedding_size].
"""
# This function assumes that the input is of shape [batch_size, seq_length,
# num_inputs].
#
# If the input is a 2D tensor of shape [batch_size, seq_length], we
# reshape to [batch_size, seq_length, 1].
if input_ids.shape.ndims == 2:
input_ids = tf.expand_dims(input_ids, axis=[-1])
embedding_table = tf.get_variable(
name=word_embedding_name,
shape=[vocab_size, embedding_size],
initializer=create_initializer(initializer_range))
flat_input_ids = tf.reshape(input_ids, [-1])
if use_one_hot_embeddings:
one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)
output = tf.matmul(one_hot_input_ids, embedding_table)
else:
output = tf.gather(embedding_table, flat_input_ids)
input_shape = get_shape_list(input_ids)
output = tf.reshape(output,
input_shape[0:-1] + [input_shape[-1] * embedding_size])
return (output, embedding_table)
def embedding_postprocessor(input_tensor,
use_token_type=False,
token_type_ids=None,
token_type_vocab_size=16,
token_type_embedding_name="token_type_embeddings",
use_position_embeddings=True,
position_embedding_name="position_embeddings",
initializer_range=0.02,
max_position_embeddings=512,
dropout_prob=0.1):
"""Performs various post-processing on a word embedding tensor.
Args:
input_tensor: float Tensor of shape [batch_size, seq_length,
embedding_size].
use_token_type: bool. Whether to add embeddings for `token_type_ids`.
token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
Must be specified if `use_token_type` is True.
token_type_vocab_size: int. The vocabulary size of `token_type_ids`.
token_type_embedding_name: string. The name of the embedding table variable
for token type ids.
use_position_embeddings: bool. Whether to add position embeddings for the
position of each token in the sequence.
position_embedding_name: string. The name of the embedding table variable
for positional embeddings.
initializer_range: float. Range of the weight initialization.
max_position_embeddings: int. Maximum sequence length that might ever be
used with this model. This can be longer than the sequence length of
input_tensor, but cannot be shorter.
dropout_prob: float. Dropout probability applied to the final output tensor.
Returns:
float tensor with same shape as `input_tensor`.
Raises:
ValueError: One of the tensor shapes or input values is invalid.
"""
input_shape = get_shape_list(input_tensor, expected_rank=3)
batch_size = input_shape[0]
seq_length = input_shape[1]
width = input_shape[2]
output = input_tensor
if use_token_type:
if token_type_ids is None:
raise ValueError("`token_type_ids` must be specified if"
"`use_token_type` is True.")
token_type_table = tf.get_variable(
name=token_type_embedding_name,
shape=[token_type_vocab_size, width],
initializer=create_initializer(initializer_range))
# This vocab will be small so we always do one-hot here, since it is always
# faster for a small vocabulary.
flat_token_type_ids = tf.reshape(token_type_ids, [-1])
one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)
token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)
token_type_embeddings = tf.reshape(token_type_embeddings,
[batch_size, seq_length, width])
output += token_type_embeddings
if use_position_embeddings:
assert_op = tf.assert_less_equal(seq_length, max_position_embeddings)
with tf.control_dependencies([assert_op]):
full_position_embeddings = tf.get_variable(
name=position_embedding_name,
shape=[max_position_embeddings, width],
initializer=create_initializer(initializer_range))
# Since the position embedding table is a learned variable, we create it
# using a (long) sequence length `max_position_embeddings`. The actual
# sequence length might be shorter than this, for faster training of
# tasks that do not have long sequences.
#
# So `full_position_embeddings` is effectively an embedding table
# for position [0, 1, 2, ..., max_position_embeddings-1], and the current
# sequence has positions [0, 1, 2, ... seq_length-1], so we can just
# perform a slice.
position_embeddings = tf.slice(full_position_embeddings, [0, 0],
[seq_length, -1])
num_dims = len(output.shape.as_list())
# Only the last two dimensions are relevant (`seq_length` and `width`), so
# we broadcast among the first dimensions, which is typically just
# the batch size.
position_broadcast_shape = []
for _ in range(num_dims - 2):
position_broadcast_shape.append(1)
position_broadcast_shape.extend([seq_length, width])
position_embeddings = tf.reshape(position_embeddings,
position_broadcast_shape)
output += position_embeddings
output = layer_norm_and_dropout(output, dropout_prob)
return output
def create_attention_mask_from_input_mask(from_tensor, to_mask):
"""Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Tensor of shape [batch_size, from_seq_length, to_seq_length].
"""
from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
batch_size = from_shape[0]
from_seq_length = from_shape[1]
to_shape = get_shape_list(to_mask, expected_rank=2)
to_seq_length = to_shape[1]
to_mask = tf.cast(
tf.reshape(to_mask, [batch_size, 1, to_seq_length]), tf.float32)
# We don't assume that `from_tensor` is a mask (although it could be). We
# don't actually care if we attend *from* padding tokens (only *to* padding)
# tokens so we create a tensor of all ones.
#
# `broadcast_ones` = [batch_size, from_seq_length, 1]
broadcast_ones = tf.ones(
shape=[batch_size, from_seq_length, 1], dtype=tf.float32)
# Here we broadcast along two dimensions to create the mask.
mask = broadcast_ones * to_mask
return mask
def attention_layer(from_tensor,
to_tensor,
attention_mask=None,
num_attention_heads=1,
size_per_head=512,
query_act=None,
key_act=None,
value_act=None,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
do_return_2d_tensor=False,
batch_size=None,
from_seq_length=None,
to_seq_length=None):
"""Performs multi-headed attention from `from_tensor` to `to_tensor`.
This is an implementation of multi-headed attention based on "Attention
is all you Need". If `from_tensor` and `to_tensor` are the same, then
this is self-attention. Each timestep in `from_tensor` attends to the
corresponding sequence in `to_tensor`, and returns a fixed-with vector.
This function first projects `from_tensor` into a "query" tensor and
`to_tensor` into "key" and "value" tensors. These are (effectively) a list
of tensors of length `num_attention_heads`, where each tensor is of shape
[batch_size, seq_length, size_per_head].
Then, the query and key tensors are dot-producted and scaled. These are
softmaxed to obtain attention probabilities. The value tensors are then
interpolated by these probabilities, then concatenated back to a single
tensor and returned.
In practice, the multi-headed attention are done with transposes and
reshapes rather than actual separate tensors.
Args:
from_tensor: float Tensor of shape [batch_size, from_seq_length,
from_width].
to_tensor: float Tensor of shape [batch_size, to_seq_length, to_width].
attention_mask: (optional) int32 Tensor of shape [batch_size,
from_seq_length, to_seq_length]. The values should be 1 or 0. The
attention scores will effectively be set to -infinity for any positions in
the mask that are 0, and will be unchanged for positions that are 1.
num_attention_heads: int. Number of attention heads.
size_per_head: int. Size of each attention head.
query_act: (optional) Activation function for the query transform.
key_act: (optional) Activation function for the key transform.
value_act: (optional) Activation function for the value transform.
attention_probs_dropout_prob: (optional) float. Dropout probability of the
attention probabilities.
initializer_range: float. Range of the weight initializer.
do_return_2d_tensor: bool. If True, the output will be of shape [batch_size
* from_seq_length, num_attention_heads * size_per_head]. If False, the
output will be of shape [batch_size, from_seq_length, num_attention_heads
* size_per_head].
batch_size: (Optional) int. If the input is 2D, this might be the batch size
of the 3D version of the `from_tensor` and `to_tensor`.
from_seq_length: (Optional) If the input is 2D, this might be the seq length
of the 3D version of the `from_tensor`.
to_seq_length: (Optional) If the input is 2D, this might be the seq length
of the 3D version of the `to_tensor`.
Returns:
float Tensor of shape [batch_size, from_seq_length,
num_attention_heads * size_per_head]. (If `do_return_2d_tensor` is
true, this will be of shape [batch_size * from_seq_length,
num_attention_heads * size_per_head]).
Raises:
ValueError: Any of the arguments or tensor shapes are invalid.
"""
def transpose_for_scores(input_tensor, batch_size, num_attention_heads,
seq_length, width):
output_tensor = tf.reshape(
input_tensor, [batch_size, seq_length, num_attention_heads, width])
output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])
return output_tensor
from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])
if len(from_shape) != len(to_shape):
raise ValueError(
"The rank of `from_tensor` must match the rank of `to_tensor`.")
if len(from_shape) == 3:
batch_size = from_shape[0]
from_seq_length = from_shape[1]
to_seq_length = to_shape[1]
elif len(from_shape) == 2:
if (batch_size is None or from_seq_length is None or to_seq_length is None):
raise ValueError(
"When passing in rank 2 tensors to attention_layer, the values "
"for `batch_size`, `from_seq_length`, and `to_seq_length` "
"must all be specified.")
# Scalar dimensions referenced here:
# B = batch size (number of sequences)
# F = `from_tensor` sequence length
# T = `to_tensor` sequence length
# N = `num_attention_heads`
# H = `size_per_head`
from_tensor_2d = reshape_to_matrix(from_tensor)
to_tensor_2d = reshape_to_matrix(to_tensor)
# `query_layer` = [B*F, N*H]
query_layer = tf.layers.dense(
from_tensor_2d,
num_attention_heads * size_per_head,
activation=query_act,
name="query",
kernel_initializer=create_initializer(initializer_range))
# `key_layer` = [B*T, N*H]
key_layer = tf.layers.dense(
to_tensor_2d,
num_attention_heads * size_per_head,
activation=key_act,
name="key",
kernel_initializer=create_initializer(initializer_range))
# `value_layer` = [B*T, N*H]
value_layer = tf.layers.dense(
to_tensor_2d,
num_attention_heads * size_per_head,
activation=value_act,
name="value",
kernel_initializer=create_initializer(initializer_range))
# `query_layer` = [B, N, F, H]
query_layer = transpose_for_scores(query_layer, batch_size,
num_attention_heads, from_seq_length,
size_per_head)
# `key_layer` = [B, N, T, H]
key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,
to_seq_length, size_per_head)
# Take the dot product between "query" and "key" to get the raw
# attention scores.
# `attention_scores` = [B, N, F, T]
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
attention_scores = tf.multiply(attention_scores,
1.0 / math.sqrt(float(size_per_head)))
if attention_mask is not None:
# `attention_mask` = [B, 1, F, T]
attention_mask = tf.expand_dims(attention_mask, axis=[1])
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
adder = (1.0 - tf.cast(attention_mask, tf.float32)) * -10000.0
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
attention_scores += adder
# Normalize the attention scores to probabilities.
# `attention_probs` = [B, N, F, T]
attention_probs = tf.nn.softmax(attention_scores)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = dropout(attention_probs, attention_probs_dropout_prob)
# `value_layer` = [B, T, N, H]
value_layer = tf.reshape(
value_layer,
[batch_size, to_seq_length, num_attention_heads, size_per_head])
# `value_layer` = [B, N, T, H]
value_layer = tf.transpose(value_layer, [0, 2, 1, 3])
# `context_layer` = [B, N, F, H]
context_layer = tf.matmul(attention_probs, value_layer)
# `context_layer` = [B, F, N, H]
context_layer = tf.transpose(context_layer, [0, 2, 1, 3])
if do_return_2d_tensor:
# `context_layer` = [B*F, N*H]
context_layer = tf.reshape(
context_layer,
[batch_size * from_seq_length, num_attention_heads * size_per_head])
else:
# `context_layer` = [B, F, N*H]
context_layer = tf.reshape(
context_layer,
[batch_size, from_seq_length, num_attention_heads * size_per_head])
return context_layer
def transformer_model(input_tensor,
attention_mask=None,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
intermediate_act_fn=gelu,
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
initializer_range=0.02,
do_return_all_layers=False):
"""Multi-headed, multi-layer Transformer from "Attention is All You Need".
This is almost an exact implementation of the original Transformer encoder.
See the original paper:
https://arxiv.org/abs/1706.03762
Also see:
https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py
Args:
input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].
attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length,
seq_length], with 1 for positions that can be attended to and 0 in
positions that should not be.
hidden_size: int. Hidden size of the Transformer.
num_hidden_layers: int. Number of layers (blocks) in the Transformer.
num_attention_heads: int. Number of attention heads in the Transformer.
intermediate_size: int. The size of the "intermediate" (a.k.a., feed
forward) layer.
intermediate_act_fn: function. The non-linear activation function to apply
to the output of the intermediate/feed-forward layer.
hidden_dropout_prob: float. Dropout probability for the hidden layers.
attention_probs_dropout_prob: float. Dropout probability of the attention
probabilities.
initializer_range: float. Range of the initializer (stddev of truncated
normal).
do_return_all_layers: Whether to also return all layers or just the final
layer.
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size], the final
hidden layer of the Transformer.
Raises:
ValueError: A Tensor shape or parameter is invalid.
"""
if hidden_size % num_attention_heads != 0:
raise ValueError(
"The hidden size (%d) is not a multiple of the number of attention "
"heads (%d)" % (hidden_size, num_attention_heads))
attention_head_size = int(hidden_size / num_attention_heads)
input_shape = get_shape_list(input_tensor, expected_rank=3)
batch_size = input_shape[0]
seq_length = input_shape[1]
input_width = input_shape[2]
# The Transformer performs sum residuals on all layers so the input needs
# to be the same as the hidden size.
if input_width != hidden_size:
raise ValueError("The width of the input tensor (%d) != hidden size (%d)" %
(input_width, hidden_size))
# We keep the representation as a 2D tensor to avoid re-shaping it back and
# forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on
# the GPU/CPU but may not be free on the TPU, so we want to minimize them to
# help the optimizer.
prev_output = reshape_to_matrix(input_tensor)
all_layer_outputs = []
for layer_idx in range(num_hidden_layers):
with tf.variable_scope("layer_%d" % layer_idx):
layer_input = prev_output
with tf.variable_scope("attention"):
attention_heads = []
with tf.variable_scope("self"):
attention_head = attention_layer(
from_tensor=layer_input,
to_tensor=layer_input,
attention_mask=attention_mask,
num_attention_heads=num_attention_heads,
size_per_head=attention_head_size,
attention_probs_dropout_prob=attention_probs_dropout_prob,
initializer_range=initializer_range,
do_return_2d_tensor=True,
batch_size=batch_size,
from_seq_length=seq_length,
to_seq_length=seq_length)
attention_heads.append(attention_head)
attention_output = None
if len(attention_heads) == 1:
attention_output = attention_heads[0]
else:
# In the case where we have other sequences, we just concatenate
# them to the self-attention head before the projection.
attention_output = tf.concat(attention_heads, axis=-1)
# Run a linear projection of `hidden_size` then add a residual
# with `layer_input`.
with tf.variable_scope("output"):
attention_output = tf.layers.dense(
attention_output,
hidden_size,
kernel_initializer=create_initializer(initializer_range))
attention_output = dropout(attention_output, hidden_dropout_prob)
attention_output = layer_norm(attention_output + layer_input)
# The activation is only applied to the "intermediate" hidden layer.
with tf.variable_scope("intermediate"):
intermediate_output = tf.layers.dense(
attention_output,
intermediate_size,
activation=intermediate_act_fn,
kernel_initializer=create_initializer(initializer_range))
# Down-project back to `hidden_size` then add the residual.
with tf.variable_scope("output"):
layer_output = tf.layers.dense(
intermediate_output,
hidden_size,
kernel_initializer=create_initializer(initializer_range))
layer_output = dropout(layer_output, hidden_dropout_prob)
layer_output = layer_norm(layer_output + attention_output)
prev_output = layer_output
all_layer_outputs.append(layer_output)
if do_return_all_layers:
final_outputs = []
for layer_output in all_layer_outputs:
final_output = reshape_from_matrix(layer_output, input_shape)
final_outputs.append(final_output)
return final_outputs
else:
final_output = reshape_from_matrix(prev_output, input_shape)
return final_output
def get_shape_list(tensor, expected_rank=None, name=None):
"""Returns a list of the shape of tensor, preferring static dimensions.
Args:
tensor: A tf.Tensor object to find the shape of.
expected_rank: (optional) int. The expected rank of `tensor`. If this is
specified and the `tensor` has a different rank, and exception will be
thrown.
name: Optional name of the tensor for the error message.
Returns:
A list of dimensions of the shape of tensor. All static dimensions will
be returned as python integers, and dynamic dimensions will be returned
as tf.Tensor scalars.
"""
if name is None:
name = tensor.name
if expected_rank is not None:
assert_rank(tensor, expected_rank, name)
shape = tensor.shape.as_list()
non_static_indexes = []
for (index, dim) in enumerate(shape):
if dim is None:
non_static_indexes.append(index)
if not non_static_indexes:
return shape
dyn_shape = tf.shape(tensor)
for index in non_static_indexes:
shape[index] = dyn_shape[index]
return shape
def reshape_to_matrix(input_tensor):
"""Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix)."""
ndims = input_tensor.shape.ndims
if ndims < 2:
raise ValueError("Input tensor must have at least rank 2. Shape = %s" %
(input_tensor.shape))
if ndims == 2:
return input_tensor
width = input_tensor.shape[-1]
output_tensor = tf.reshape(input_tensor, [-1, width])
return output_tensor
def reshape_from_matrix(output_tensor, orig_shape_list):
"""Reshapes a rank 2 tensor back to its original rank >= 2 tensor."""
if len(orig_shape_list) == 2:
return output_tensor
output_shape = get_shape_list(output_tensor)
orig_dims = orig_shape_list[0:-1]
width = output_shape[-1]
return tf.reshape(output_tensor, orig_dims + [width])
def assert_rank(tensor, expected_rank, name=None):
"""Raises an exception if the tensor rank is not of the expected rank.
Args:
tensor: A tf.Tensor to check the rank of.
expected_rank: Python integer or list of integers, expected rank.
name: Optional name of the tensor for the error message.
Raises:
ValueError: If the expected shape doesn't match the actual shape.
"""
if name is None:
name = tensor.name
expected_rank_dict = {}
if isinstance(expected_rank, six.integer_types):
expected_rank_dict[expected_rank] = True
else:
for x in expected_rank:
expected_rank_dict[x] = True
actual_rank = tensor.shape.ndims
if actual_rank not in expected_rank_dict:
scope_name = tf.get_variable_scope().name
raise ValueError(
"For the tensor `%s` in scope `%s`, the actual rank "
"`%d` (shape = %s) is not equal to the expected rank `%s`" %
(name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))
| 37,922 | 37.422492 | 93 | py |
CLUE | CLUE-master/baselines/models/ernie/extract_features.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Extract pre-computed feature vectors from BERT."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import codecs
import collections
import json
import re
import modeling
import tokenization
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_string("input_file", None, "")
flags.DEFINE_string("output_file", None, "")
flags.DEFINE_string("layers", "-1,-2,-3,-4", "")
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_integer(
"max_seq_length", 128,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded.")
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_integer("batch_size", 32, "Batch size for predictions.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
flags.DEFINE_string("master", None,
"If using a TPU, the address of the master.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
flags.DEFINE_bool(
"use_one_hot_embeddings", False,
"If True, tf.one_hot will be used for embedding lookups, otherwise "
"tf.nn.embedding_lookup will be used. On TPUs, this should be True "
"since it is much faster.")
class InputExample(object):
def __init__(self, unique_id, text_a, text_b):
self.unique_id = unique_id
self.text_a = text_a
self.text_b = text_b
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids):
self.unique_id = unique_id
self.tokens = tokens
self.input_ids = input_ids
self.input_mask = input_mask
self.input_type_ids = input_type_ids
def input_fn_builder(features, seq_length):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
all_unique_ids = []
all_input_ids = []
all_input_mask = []
all_input_type_ids = []
for feature in features:
all_unique_ids.append(feature.unique_id)
all_input_ids.append(feature.input_ids)
all_input_mask.append(feature.input_mask)
all_input_type_ids.append(feature.input_type_ids)
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
num_examples = len(features)
# This is for demo purposes and does NOT scale to large data sets. We do
# not use Dataset.from_generator() because that uses tf.py_func which is
# not TPU compatible. The right way to load data is with TFRecordReader.
d = tf.data.Dataset.from_tensor_slices({
"unique_ids":
tf.constant(all_unique_ids, shape=[num_examples], dtype=tf.int32),
"input_ids":
tf.constant(
all_input_ids, shape=[num_examples, seq_length],
dtype=tf.int32),
"input_mask":
tf.constant(
all_input_mask,
shape=[num_examples, seq_length],
dtype=tf.int32),
"input_type_ids":
tf.constant(
all_input_type_ids,
shape=[num_examples, seq_length],
dtype=tf.int32),
})
d = d.batch(batch_size=batch_size, drop_remainder=False)
return d
return input_fn
def model_fn_builder(bert_config, init_checkpoint, layer_indexes, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
unique_ids = features["unique_ids"]
input_ids = features["input_ids"]
input_mask = features["input_mask"]
input_type_ids = features["input_type_ids"]
model = modeling.BertModel(
config=bert_config,
is_training=False,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=input_type_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
if mode != tf.estimator.ModeKeys.PREDICT:
raise ValueError("Only PREDICT modes are supported: %s" % (mode))
tvars = tf.trainable_variables()
scaffold_fn = None
(assignment_map,
initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(
tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
all_layers = model.get_all_encoder_layers()
predictions = {
"unique_id": unique_ids,
}
for (i, layer_index) in enumerate(layer_indexes):
predictions["layer_output_%d" % i] = all_layers[layer_index]
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
return output_spec
return model_fn
def convert_examples_to_features(examples, seq_length, tokenizer):
"""Loads a data file into a list of `InputBatch`s."""
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
if tokens_b:
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for [CLS], [SEP], [SEP] with "- 3"
_truncate_seq_pair(tokens_a, tokens_b, seq_length - 3)
else:
# Account for [CLS] and [SEP] with "- 2"
if len(tokens_a) > seq_length - 2:
tokens_a = tokens_a[0:(seq_length - 2)]
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens = []
input_type_ids = []
tokens.append("[CLS]")
input_type_ids.append(0)
for token in tokens_a:
tokens.append(token)
input_type_ids.append(0)
tokens.append("[SEP]")
input_type_ids.append(0)
if tokens_b:
for token in tokens_b:
tokens.append(token)
input_type_ids.append(1)
tokens.append("[SEP]")
input_type_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < seq_length:
input_ids.append(0)
input_mask.append(0)
input_type_ids.append(0)
assert len(input_ids) == seq_length
assert len(input_mask) == seq_length
assert len(input_type_ids) == seq_length
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("unique_id: %s" % (example.unique_id))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info(
"input_type_ids: %s" % " ".join([str(x) for x in input_type_ids]))
features.append(
InputFeatures(
unique_id=example.unique_id,
tokens=tokens,
input_ids=input_ids,
input_mask=input_mask,
input_type_ids=input_type_ids))
return features
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def read_examples(input_file):
"""Read a list of `InputExample`s from an input file."""
examples = []
unique_id = 0
with tf.gfile.GFile(input_file, "r") as reader:
while True:
line = tokenization.convert_to_unicode(reader.readline())
if not line:
break
line = line.strip()
text_a = None
text_b = None
m = re.match(r"^(.*) \|\|\| (.*)$", line)
if m is None:
text_a = line
else:
text_a = m.group(1)
text_b = m.group(2)
examples.append(
InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b))
unique_id += 1
return examples
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
layer_indexes = [int(x) for x in FLAGS.layers.split(",")]
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
master=FLAGS.master,
tpu_config=tf.contrib.tpu.TPUConfig(
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
examples = read_examples(FLAGS.input_file)
features = convert_examples_to_features(
examples=examples, seq_length=FLAGS.max_seq_length, tokenizer=tokenizer)
unique_id_to_feature = {}
for feature in features:
unique_id_to_feature[feature.unique_id] = feature
model_fn = model_fn_builder(
bert_config=bert_config,
init_checkpoint=FLAGS.init_checkpoint,
layer_indexes=layer_indexes,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_one_hot_embeddings)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
predict_batch_size=FLAGS.batch_size)
input_fn = input_fn_builder(
features=features, seq_length=FLAGS.max_seq_length)
with codecs.getwriter("utf-8")(tf.gfile.Open(FLAGS.output_file,
"w")) as writer:
for result in estimator.predict(input_fn, yield_single_examples=True):
unique_id = int(result["unique_id"])
feature = unique_id_to_feature[unique_id]
output_json = collections.OrderedDict()
output_json["linex_index"] = unique_id
all_features = []
for (i, token) in enumerate(feature.tokens):
all_layers = []
for (j, layer_index) in enumerate(layer_indexes):
layer_output = result["layer_output_%d" % j]
layers = collections.OrderedDict()
layers["index"] = layer_index
layers["values"] = [
round(float(x), 6) for x in layer_output[i:(i + 1)].flat
]
all_layers.append(layers)
features = collections.OrderedDict()
features["token"] = token
features["layers"] = all_layers
all_features.append(features)
output_json["features"] = all_features
writer.write(json.dumps(output_json) + "\n")
if __name__ == "__main__":
flags.mark_flag_as_required("input_file")
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("init_checkpoint")
flags.mark_flag_as_required("output_file")
tf.app.run()
| 13,898 | 32.092857 | 82 | py |
CLUE | CLUE-master/baselines/models/ernie/modeling_test.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import json
import random
import re
import modeling
import six
import tensorflow as tf
class BertModelTest(tf.test.TestCase):
class BertModelTester(object):
def __init__(self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
vocab_size=99,
hidden_size=32,
num_hidden_layers=5,
num_attention_heads=4,
intermediate_size=37,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=16,
initializer_range=0.02,
scope=None):
self.parent = parent
self.batch_size = batch_size
self.seq_length = seq_length
self.is_training = is_training
self.use_input_mask = use_input_mask
self.use_token_type_ids = use_token_type_ids
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
self.scope = scope
def create_model(self):
input_ids = BertModelTest.ids_tensor([self.batch_size, self.seq_length],
self.vocab_size)
input_mask = None
if self.use_input_mask:
input_mask = BertModelTest.ids_tensor(
[self.batch_size, self.seq_length], vocab_size=2)
token_type_ids = None
if self.use_token_type_ids:
token_type_ids = BertModelTest.ids_tensor(
[self.batch_size, self.seq_length], self.type_vocab_size)
config = modeling.BertConfig(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
max_position_embeddings=self.max_position_embeddings,
type_vocab_size=self.type_vocab_size,
initializer_range=self.initializer_range)
model = modeling.BertModel(
config=config,
is_training=self.is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=token_type_ids,
scope=self.scope)
outputs = {
"embedding_output": model.get_embedding_output(),
"sequence_output": model.get_sequence_output(),
"pooled_output": model.get_pooled_output(),
"all_encoder_layers": model.get_all_encoder_layers(),
}
return outputs
def check_output(self, result):
self.parent.assertAllEqual(
result["embedding_output"].shape,
[self.batch_size, self.seq_length, self.hidden_size])
self.parent.assertAllEqual(
result["sequence_output"].shape,
[self.batch_size, self.seq_length, self.hidden_size])
self.parent.assertAllEqual(result["pooled_output"].shape,
[self.batch_size, self.hidden_size])
def test_default(self):
self.run_tester(BertModelTest.BertModelTester(self))
def test_config_to_json_string(self):
config = modeling.BertConfig(vocab_size=99, hidden_size=37)
obj = json.loads(config.to_json_string())
self.assertEqual(obj["vocab_size"], 99)
self.assertEqual(obj["hidden_size"], 37)
def run_tester(self, tester):
with self.test_session() as sess:
ops = tester.create_model()
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess.run(init_op)
output_result = sess.run(ops)
tester.check_output(output_result)
self.assert_all_tensors_reachable(sess, [init_op, ops])
@classmethod
def ids_tensor(cls, shape, vocab_size, rng=None, name=None):
"""Creates a random int32 tensor of the shape within the vocab size."""
if rng is None:
rng = random.Random()
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append(rng.randint(0, vocab_size - 1))
return tf.constant(value=values, dtype=tf.int32, shape=shape, name=name)
def assert_all_tensors_reachable(self, sess, outputs):
"""Checks that all the tensors in the graph are reachable from outputs."""
graph = sess.graph
ignore_strings = [
"^.*/assert_less_equal/.*$",
"^.*/dilation_rate$",
"^.*/Tensordot/concat$",
"^.*/Tensordot/concat/axis$",
"^testing/.*$",
]
ignore_regexes = [re.compile(x) for x in ignore_strings]
unreachable = self.get_unreachable_ops(graph, outputs)
filtered_unreachable = []
for x in unreachable:
do_ignore = False
for r in ignore_regexes:
m = r.match(x.name)
if m is not None:
do_ignore = True
if do_ignore:
continue
filtered_unreachable.append(x)
unreachable = filtered_unreachable
self.assertEqual(
len(unreachable), 0, "The following ops are unreachable: %s" %
(" ".join([x.name for x in unreachable])))
@classmethod
def get_unreachable_ops(cls, graph, outputs):
"""Finds all of the tensors in graph that are unreachable from outputs."""
outputs = cls.flatten_recursive(outputs)
output_to_op = collections.defaultdict(list)
op_to_all = collections.defaultdict(list)
assign_out_to_in = collections.defaultdict(list)
for op in graph.get_operations():
for x in op.inputs:
op_to_all[op.name].append(x.name)
for y in op.outputs:
output_to_op[y.name].append(op.name)
op_to_all[op.name].append(y.name)
if str(op.type) == "Assign":
for y in op.outputs:
for x in op.inputs:
assign_out_to_in[y.name].append(x.name)
assign_groups = collections.defaultdict(list)
for out_name in assign_out_to_in.keys():
name_group = assign_out_to_in[out_name]
for n1 in name_group:
assign_groups[n1].append(out_name)
for n2 in name_group:
if n1 != n2:
assign_groups[n1].append(n2)
seen_tensors = {}
stack = [x.name for x in outputs]
while stack:
name = stack.pop()
if name in seen_tensors:
continue
seen_tensors[name] = True
if name in output_to_op:
for op_name in output_to_op[name]:
if op_name in op_to_all:
for input_name in op_to_all[op_name]:
if input_name not in stack:
stack.append(input_name)
expanded_names = []
if name in assign_groups:
for assign_name in assign_groups[name]:
expanded_names.append(assign_name)
for expanded_name in expanded_names:
if expanded_name not in stack:
stack.append(expanded_name)
unreachable_ops = []
for op in graph.get_operations():
is_unreachable = False
all_names = [x.name for x in op.inputs] + [x.name for x in op.outputs]
for name in all_names:
if name not in seen_tensors:
is_unreachable = True
if is_unreachable:
unreachable_ops.append(op)
return unreachable_ops
@classmethod
def flatten_recursive(cls, item):
"""Flattens (potentially nested) a tuple/dictionary/list to a list."""
output = []
if isinstance(item, list):
output.extend(item)
elif isinstance(item, tuple):
output.extend(list(item))
elif isinstance(item, dict):
for (_, v) in six.iteritems(item):
output.append(v)
else:
return [item]
flat_output = []
for x in output:
flat_output.extend(cls.flatten_recursive(x))
return flat_output
if __name__ == "__main__":
tf.test.main()
| 9,191 | 32.064748 | 78 | py |
CLUE | CLUE-master/baselines/models/ernie/conlleval.py | # Python version of the evaluation script from CoNLL'00-
# Originates from: https://github.com/spyysalo/conlleval.py
# Intentional differences:
# - accept any space as delimiter by default
# - optional file argument (default STDIN)
# - option to set boundary (-b argument)
# - LaTeX output (-l argument) not supported
# - raw tags (-r argument) not supported
# add function :evaluate(predicted_label, ori_label): which will not read from file
import sys
import re
import codecs
from collections import defaultdict, namedtuple
ANY_SPACE = '<SPACE>'
class FormatError(Exception):
pass
Metrics = namedtuple('Metrics', 'tp fp fn prec rec fscore')
class EvalCounts(object):
def __init__(self):
self.correct_chunk = 0 # number of correctly identified chunks
self.correct_tags = 0 # number of correct chunk tags
self.found_correct = 0 # number of chunks in corpus
self.found_guessed = 0 # number of identified chunks
self.token_counter = 0 # token counter (ignores sentence breaks)
# counts by type
self.t_correct_chunk = defaultdict(int)
self.t_found_correct = defaultdict(int)
self.t_found_guessed = defaultdict(int)
def parse_args(argv):
import argparse
parser = argparse.ArgumentParser(
description='evaluate tagging results using CoNLL criteria',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
arg = parser.add_argument
arg('-b', '--boundary', metavar='STR', default='-X-',
help='sentence boundary')
arg('-d', '--delimiter', metavar='CHAR', default=ANY_SPACE,
help='character delimiting items in input')
arg('-o', '--otag', metavar='CHAR', default='O',
help='alternative outside tag')
arg('file', nargs='?', default=None)
return parser.parse_args(argv)
def parse_tag(t):
m = re.match(r'^([^-]*)-(.*)$', t)
return m.groups() if m else (t, '')
def evaluate(iterable, options=None):
if options is None:
options = parse_args([]) # use defaults
counts = EvalCounts()
num_features = None # number of features per line
in_correct = False # currently processed chunks is correct until now
last_correct = 'O' # previous chunk tag in corpus
last_correct_type = '' # type of previously identified chunk tag
last_guessed = 'O' # previously identified chunk tag
last_guessed_type = '' # type of previous chunk tag in corpus
for line in iterable:
line = line.rstrip('\r\n')
if options.delimiter == ANY_SPACE:
features = line.split()
else:
features = line.split(options.delimiter)
if num_features is None:
num_features = len(features)
elif num_features != len(features) and len(features) != 0:
raise FormatError('unexpected number of features: %d (%d)' %
(len(features), num_features))
if len(features) == 0 or features[0] == options.boundary:
features = [options.boundary, 'O', 'O']
if len(features) < 3:
raise FormatError('unexpected number of features in line %s' % line)
guessed, guessed_type = parse_tag(features.pop())
correct, correct_type = parse_tag(features.pop())
first_item = features.pop(0)
if first_item == options.boundary:
guessed = 'O'
end_correct = end_of_chunk(last_correct, correct,
last_correct_type, correct_type)
end_guessed = end_of_chunk(last_guessed, guessed,
last_guessed_type, guessed_type)
start_correct = start_of_chunk(last_correct, correct,
last_correct_type, correct_type)
start_guessed = start_of_chunk(last_guessed, guessed,
last_guessed_type, guessed_type)
if in_correct:
if (end_correct and end_guessed and
last_guessed_type == last_correct_type):
in_correct = False
counts.correct_chunk += 1
counts.t_correct_chunk[last_correct_type] += 1
elif (end_correct != end_guessed or guessed_type != correct_type):
in_correct = False
if start_correct and start_guessed and guessed_type == correct_type:
in_correct = True
if start_correct:
counts.found_correct += 1
counts.t_found_correct[correct_type] += 1
if start_guessed:
counts.found_guessed += 1
counts.t_found_guessed[guessed_type] += 1
if first_item != options.boundary:
if correct == guessed and guessed_type == correct_type:
counts.correct_tags += 1
counts.token_counter += 1
last_guessed = guessed
last_correct = correct
last_guessed_type = guessed_type
last_correct_type = correct_type
if in_correct:
counts.correct_chunk += 1
counts.t_correct_chunk[last_correct_type] += 1
return counts
def uniq(iterable):
seen = set()
return [i for i in iterable if not (i in seen or seen.add(i))]
def calculate_metrics(correct, guessed, total):
tp, fp, fn = correct, guessed-correct, total-correct
p = 0 if tp + fp == 0 else 1.*tp / (tp + fp)
r = 0 if tp + fn == 0 else 1.*tp / (tp + fn)
f = 0 if p + r == 0 else 2 * p * r / (p + r)
return Metrics(tp, fp, fn, p, r, f)
def metrics(counts):
c = counts
overall = calculate_metrics(
c.correct_chunk, c.found_guessed, c.found_correct
)
by_type = {}
for t in uniq(list(c.t_found_correct) + list(c.t_found_guessed)):
by_type[t] = calculate_metrics(
c.t_correct_chunk[t], c.t_found_guessed[t], c.t_found_correct[t]
)
return overall, by_type
def report(counts, out=None):
if out is None:
out = sys.stdout
overall, by_type = metrics(counts)
c = counts
out.write('processed %d tokens with %d phrases; ' %
(c.token_counter, c.found_correct))
out.write('found: %d phrases; correct: %d.\n' %
(c.found_guessed, c.correct_chunk))
if c.token_counter > 0:
out.write('accuracy: %6.2f%%; ' %
(100.*c.correct_tags/c.token_counter))
out.write('precision: %6.2f%%; ' % (100.*overall.prec))
out.write('recall: %6.2f%%; ' % (100.*overall.rec))
out.write('FB1: %6.2f\n' % (100.*overall.fscore))
for i, m in sorted(by_type.items()):
out.write('%17s: ' % i)
out.write('precision: %6.2f%%; ' % (100.*m.prec))
out.write('recall: %6.2f%%; ' % (100.*m.rec))
out.write('FB1: %6.2f %d\n' % (100.*m.fscore, c.t_found_guessed[i]))
def report_notprint(counts, out=None):
if out is None:
out = sys.stdout
overall, by_type = metrics(counts)
c = counts
final_report = []
line = []
line.append('processed %d tokens with %d phrases; ' %
(c.token_counter, c.found_correct))
line.append('found: %d phrases; correct: %d.\n' %
(c.found_guessed, c.correct_chunk))
final_report.append("".join(line))
if c.token_counter > 0:
line = []
line.append('accuracy: %6.2f%%; ' %
(100.*c.correct_tags/c.token_counter))
line.append('precision: %6.2f%%; ' % (100.*overall.prec))
line.append('recall: %6.2f%%; ' % (100.*overall.rec))
line.append('FB1: %6.2f\n' % (100.*overall.fscore))
final_report.append("".join(line))
for i, m in sorted(by_type.items()):
line = []
line.append('%17s: ' % i)
line.append('precision: %6.2f%%; ' % (100.*m.prec))
line.append('recall: %6.2f%%; ' % (100.*m.rec))
line.append('FB1: %6.2f %d\n' % (100.*m.fscore, c.t_found_guessed[i]))
final_report.append("".join(line))
return final_report
def end_of_chunk(prev_tag, tag, prev_type, type_):
# check if a chunk ended between the previous and current word
# arguments: previous and current chunk tags, previous and current types
chunk_end = False
if prev_tag == 'E': chunk_end = True
if prev_tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'B': chunk_end = True
if prev_tag == 'B' and tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'O': chunk_end = True
if prev_tag == 'I' and tag == 'B': chunk_end = True
if prev_tag == 'I' and tag == 'S': chunk_end = True
if prev_tag == 'I' and tag == 'O': chunk_end = True
if prev_tag != 'O' and prev_tag != '.' and prev_type != type_:
chunk_end = True
# these chunks are assumed to have length 1
if prev_tag == ']': chunk_end = True
if prev_tag == '[': chunk_end = True
return chunk_end
def start_of_chunk(prev_tag, tag, prev_type, type_):
# check if a chunk started between the previous and current word
# arguments: previous and current chunk tags, previous and current types
chunk_start = False
if tag == 'B': chunk_start = True
if tag == 'S': chunk_start = True
if prev_tag == 'E' and tag == 'E': chunk_start = True
if prev_tag == 'E' and tag == 'I': chunk_start = True
if prev_tag == 'S' and tag == 'E': chunk_start = True
if prev_tag == 'S' and tag == 'I': chunk_start = True
if prev_tag == 'O' and tag == 'E': chunk_start = True
if prev_tag == 'O' and tag == 'I': chunk_start = True
if tag != 'O' and tag != '.' and prev_type != type_:
chunk_start = True
# these chunks are assumed to have length 1
if tag == '[': chunk_start = True
if tag == ']': chunk_start = True
return chunk_start
def return_report(input_file):
with codecs.open(input_file, "r", "utf8") as f:
counts = evaluate(f)
return report_notprint(counts)
def main(argv):
args = parse_args(argv[1:])
if args.file is None:
counts = evaluate(sys.stdin, args)
else:
with open(args.file) as f:
counts = evaluate(f, args)
report(counts)
if __name__ == '__main__':
sys.exit(main(sys.argv)) | 10,196 | 32.99 | 83 | py |
CLUE | CLUE-master/baselines/models/ernie/optimization_test.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import optimization
import tensorflow as tf
class OptimizationTest(tf.test.TestCase):
def test_adam(self):
with self.test_session() as sess:
w = tf.get_variable(
"w",
shape=[3],
initializer=tf.constant_initializer([0.1, -0.2, -0.1]))
x = tf.constant([0.4, 0.2, -0.5])
loss = tf.reduce_mean(tf.square(x - w))
tvars = tf.trainable_variables()
grads = tf.gradients(loss, tvars)
global_step = tf.train.get_or_create_global_step()
optimizer = optimization.AdamWeightDecayOptimizer(learning_rate=0.2)
train_op = optimizer.apply_gradients(zip(grads, tvars), global_step)
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess.run(init_op)
for _ in range(100):
sess.run(train_op)
w_np = sess.run(w)
self.assertAllClose(w_np.flat, [0.4, 0.2, -0.5], rtol=1e-2, atol=1e-2)
if __name__ == "__main__":
tf.test.main()
| 1,721 | 34.142857 | 76 | py |
CLUE | CLUE-master/baselines/models/ernie/run_ner.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BERT finetuning runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
import modeling
import optimization
import tokenization
import tensorflow as tf
from sklearn.metrics import f1_score, precision_score, recall_score
from tensorflow.python.ops import math_ops
import tf_metrics
import pickle
import codecs
import sys
import sys
reload(sys)
sys.setdefaultencoding('utf8')
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_string(
"data_dir", None,
"The input datadir.",
)
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model."
)
flags.DEFINE_string(
"task_name", None, "The name of the task to train."
)
flags.DEFINE_string(
"token_name", "full", "The name of the task to train."
)
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written."
)
## Other parameters
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model)."
)
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text."
)
flags.DEFINE_integer(
"max_seq_length", 128,
"The maximum total input sequence length after WordPiece tokenization."
)
flags.DEFINE_bool(
"do_train", False,
"Whether to run training."
)
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
flags.DEFINE_bool("do_predict", False, "Whether to run the model in inference mode on the test set.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predict.")
flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
flags.DEFINE_float("num_train_epochs", 3.0, "Total number of training epochs to perform.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text, label=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text = text
self.label = label
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, input_ids, input_mask, segment_ids, label_ids, label_mask):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_ids = label_ids
self.label_mask = label_mask
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
@classmethod
def _read_data(cls, input_file):
"""Reads a BIO data."""
with open(input_file) as f:
lines = []
words = []
labels = []
for line in f:
contends = line.strip()
word = line.strip().split(' ')[0]
label = line.strip().split(' ')[-1]
if contends.startswith("-DOCSTART-"):
words.append('')
continue
if len(contends) == 0 and words[-1] == '.':
l = ' '.join([label for label in labels if len(label) > 0])
w = ' '.join([word for word in words if len(word) > 0])
lines.append([l, w])
words = []
labels = []
continue
if len(contends) == 0:
continue
words.append(word)
labels.append(label)
return lines
class NerProcessor(DataProcessor):
def get_train_examples(self, data_dir):
return self._create_example(
self._read_data(os.path.join(data_dir, "train.txt")), "train"
)
def get_dev_examples(self, data_dir):
return self._create_example(
self._read_data(os.path.join(data_dir, "dev.txt")), "dev"
)
def get_test_examples(self, data_dir):
return self._create_example(
self._read_data(os.path.join(data_dir, "test.txt")), "test")
def get_labels(self):
# return ["I-MISC", "I-PER", "I-ORG", "I-LOC", "O", "X", "[CLS]", "[SEP]"]
return ["B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", "O", "X", "[CLS]", "[SEP]"]
def _create_example(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text = tokenization.convert_to_unicode(line[1])
label = tokenization.convert_to_unicode(line[0])
examples.append(InputExample(guid=guid, text=text, label=label))
return examples
class WeiboNERProcessor(DataProcessor):
def __init_(self):
self.labels = set()
def get_train_examples(self, data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "weiboNER.conll.train")), "train"
)
def get_dev_examples(self, data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "weiboNER.conll.dev")), "dev"
)
def get_test_examples(self,data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "weiboNER.conll.test")), "test")
def get_labels(self):
return ['I-PER.NOM', 'I-PER.NAM', 'I-GPE.NAM', 'I-ORG.NAM', 'I-ORG.NOM', 'I-LOC.NAM', 'I-LOC.NOM', "O", "X", "[CLS]", "[SEP]"]
# return ['B-PER.NOM', 'I-PER.NOM', 'B-LOC.NAM', 'B-PER.NAM', 'I-PER.NAM', 'B-GPE.NAM', 'I-GPE.NAM', 'B-ORG.NAM', 'I-ORG.NAM', 'B-ORG.NOM', 'I-ORG.NOM', 'I-LOC.NAM', 'B-LOC.NOM', 'I-LOC.NOM', "O", "X", "[CLS]", "[SEP]"]
def _create_example(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text = tokenization.convert_to_unicode(line[1])
label = tokenization.convert_to_unicode(line[0])
examples.append(InputExample(guid=guid, text=text, label=label))
return examples
def _read_raw(self, input_file):
with codecs.open(input_file, 'r', encoding='utf-8') as f:
lines = []
words = []
labels = []
for line in f:
contends = line.strip()
tokens = contends.split()
if len(tokens) == 2:
words.append(tokens[0])
label = tokens[-1]
if label[0] == 'B':
label = "I" + label[1:]
labels.append(label)
else:
if len(contends) == 0 and len(words) > 0:
label = []
word = []
for l, w in zip(labels, words):
if len(l) > 0 and len(w) > 0:
label.append(l)
# self.labels.add(l)
word.append(w)
lines.append([' '.join(label), ' '.join(word)])
words = []
labels = []
continue
if contends.startswith("-DOCSTART-"):
continue
return lines
class MsraNERProcessor(DataProcessor):
def __init_(self):
self.labels = set()
def get_train_examples(self, data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "train1.txt")), "train"
)
def get_dev_examples(self, data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "testright1.txt")), "dev"
)
def get_test_examples(self,data_dir):
return self._create_example(
self._read_raw(os.path.join(data_dir, "testright1.txt")), "test")
def get_labels(self):
return ['B-PERSON', 'I-PERSON', 'B-LOCATION', 'I-LOCATION', 'B-ORGANIZATION', 'I-ORGANIZATION', "O", "[CLS]", "[SEP]", "X"]
def _create_example(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text = tokenization.convert_to_unicode(line[1])
label = tokenization.convert_to_unicode(line[0])
examples.append(InputExample(guid=guid, text=text, label=label))
return examples
def _read_raw(self, input_file):
with codecs.open(input_file, 'r', encoding='utf-8') as f:
lines = []
chars = []
labels = []
len_count = []
for line in f:
contends = line.strip()
tokens = contends.split()
for token in tokens:
word, label = token.split('/')
if label == "nr":
chars = chars + list(word)
labels = labels + ['B-PERSON'] + ['I-PERSON']*(len(word)-1)
elif label == "ns":
chars = chars + list(word)
labels = labels + ['B-LOCATION'] + ['I-LOCATION']*(len(word)-1)
elif label == "nt":
chars = chars + list(word)
labels = labels + ['B-ORGANIZATION'] + ['I-ORGANIZATION']*(len(word)-1)
else:
assert label == "o"
chars = chars + list(word)
labels = labels + ["O"] * len(word)
lines.append([' '.join(labels), ' '.join(chars)])
len_count.append(len(chars))
chars = []
labels = []
return lines
def write_tokens(tokens, mode):
if mode == "test":
path = os.path.join(FLAGS.output_dir, "token_" + mode + ".txt")
wf = open(path, 'a')
for token in tokens:
if token != "**NULL**":
wf.write(token + '\n')
wf.close()
def convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer, output_dir, mode):
label_map = {}
for (i, label) in enumerate(label_list, 1):
label_map[label] = i
if not os.path.exists(os.path.join(output_dir, 'label2id.pkl')):
with open(os.path.join(output_dir, 'label2id.pkl'), 'wb') as w:
pickle.dump(label_map, w)
textlist = example.text.split(' ')
labellist = example.label.split(' ')
tokens = []
labels = []
label_mask = []
for i, word in enumerate(textlist):
token = tokenizer.tokenize(word)
tokens.extend(token)
label_1 = labellist[i]
for m in range(len(token)):
if m == 0:
labels.append(label_1)
else:
labels.append("X")
# tokens = tokenizer.tokenize(example.text)
if len(tokens) >= max_seq_length - 1:
tokens = tokens[0:(max_seq_length - 2)]
labels = labels[0:(max_seq_length - 2)]
ntokens = []
segment_ids = []
label_ids = []
ntokens.append("[CLS]")
segment_ids.append(0)
# append("O") or append("[CLS]") not sure!
label_ids.append(label_map["[CLS]"])
label_mask.append(0) # not to predict and train
for i, token in enumerate(tokens):
ntokens.append(token)
segment_ids.append(0)
label_ids.append(label_map[labels[i]])
if labels[i] == 'X':
label_mask.append(0)
else:
label_mask.append(1)
ntokens.append("[SEP]")
segment_ids.append(0)
label_mask.append(0)
# append("O") or append("[SEP]") not sure!
label_ids.append(label_map["[SEP]"])
input_ids = tokenizer.convert_tokens_to_ids(ntokens)
input_mask = [1] * len(input_ids)
# label_mask = [1] * len(input_ids)
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
# we don't concerned about it!
label_ids.append(0)
ntokens.append("**NULL**")
label_mask.append(0)
# print(len(input_ids))
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
assert len(label_ids) == max_seq_length
assert len(label_mask) == max_seq_length
if ex_index < 5:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label_ids: %s" % " ".join([str(x) for x in label_ids]))
tf.logging.info("label_mask: %s" % " ".join([str(x) for x in label_mask]))
# tf.logging.info("label_mask: %s" % " ".join([str(x) for x in label_mask]))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_ids=label_ids,
label_mask = label_mask
)
write_tokens(ntokens, mode)
return feature
def file_based_convert_examples_to_features(
examples, label_list, max_seq_length, tokenizer, output_file, output_dir, mode=None
):
writer = tf.python_io.TFRecordWriter(output_file)
for (ex_index, example) in enumerate(examples):
if ex_index % 5000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer, output_dir, mode)
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
features = collections.OrderedDict()
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["label_ids"] = create_int_feature(feature.label_ids)
features["label_mask"] = create_int_feature(feature.label_mask)
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder):
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_mask": tf.FixedLenFeature([seq_length], tf.int64),
}
def _decode_record(record, name_to_features):
example = tf.parse_single_example(record, name_to_features)
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
batch_size = params["batch_size"]
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.apply(tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder
))
return d
return input_fn
def create_model(bert_config, is_training, input_ids, input_mask, label_mask,
segment_ids, labels, num_labels, use_one_hot_embeddings):
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings
)
output_layer = model.get_sequence_output()
hidden_size = output_layer.shape[-1].value
output_weight = tf.get_variable(
"output_weights", [num_labels, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02)
)
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer()
)
with tf.variable_scope("loss"):
if is_training:
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
output_layer = tf.reshape(output_layer, [-1, hidden_size])
logits = tf.matmul(output_layer, output_weight, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
logits = tf.reshape(logits, [-1, FLAGS.max_seq_length, num_labels])
# mask = tf.cast(input_mask,tf.float32)
# loss = tf.contrib.seq2seq.sequence_loss(logits,labels,mask)
# return (loss, logits, predict)
##########################################################################
log_probs = tf.nn.log_softmax(logits, axis=-1)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
mask = tf.cast(label_mask, tf.float32)
mask_example_loss = per_example_loss * mask
loss = tf.reduce_sum(mask_example_loss)
probabilities = tf.nn.softmax(logits, axis=-1)
predict = tf.argmax(probabilities, axis=-1)
return (loss, mask_example_loss, logits, predict)
##########################################################################
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
def model_fn(features, labels, mode, params):
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]
label_mask = features["label_mask"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(total_loss, per_example_loss, logits, predicts) = create_model(
bert_config, is_training, input_ids, input_mask, label_mask, segment_ids, label_ids,
num_labels, use_one_hot_embeddings)
tvars = tf.trainable_variables()
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars,
init_checkpoint)
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
hook_dict = {}
hook_dict['loss'] = total_loss
hook_dict['global_steps'] = tf.train.get_or_create_global_step()
logging_hook = tf.train.LoggingTensorHook(
hook_dict, every_n_iter=200)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn,
training_hooks=[logging_hook])
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits):
# def metric_fn(label_ids, logits):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
# labels = []
# for i, x in enumerate()
predict_labels = []
# for i in range(1, num_labels - 4):
# predict_labels.append(i)
# precision = tf_metrics.precision(label_ids, predictions, num_labels, predict_labels, average="macro")
# recall = tf_metrics.recall(label_ids, predictions, num_labels, predict_labels, average="macro")
# f = tf_metrics.f1(label_ids, predictions, num_labels, predict_labels, average="macro")
precision = tf_metrics.precision(label_ids, predictions, num_labels, average="macro")
recall = tf_metrics.recall(label_ids, predictions, num_labels, average="macro")
f = tf_metrics.f1(label_ids, predictions, num_labels, average="macro")
#
return {
"eval_precision": precision,
"eval_recall": recall,
"eval_f": f,
# "eval_loss": loss,
}
eval_metrics = (metric_fn, [per_example_loss, label_ids, logits])
# eval_metrics = (metric_fn, [label_ids, logits])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions=predicts, scaffold_fn=scaffold_fn
)
return output_spec
return model_fn
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"ner": NerProcessor,
"weiboner": WeiboNERProcessor,
"msraner": MsraNERProcessor
}
# if not FLAGS.do_train and not FLAGS.do_eval:
# raise ValueError("At least one of `do_train` or `do_eval` must be True.")
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
if FLAGS.max_seq_length > bert_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, bert_config.max_position_embeddings))
if not os.path.exists(FLAGS.output_dir):
os.mkdir(FLAGS.output_dir)
task_name = FLAGS.task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
label_list = processor.get_labels()
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = processor.get_train_examples(FLAGS.data_dir)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
print(num_train_steps)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
model_fn = model_fn_builder(
bert_config=bert_config,
num_labels=len(label_list) + 1,
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file, FLAGS.output_dir)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = file_based_input_fn_builder(
input_file=train_file,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_eval:
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")
file_based_convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file, FLAGS.output_dir)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d", len(eval_examples))
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
eval_steps = None
if FLAGS.use_tpu:
eval_steps = int(len(eval_examples) / FLAGS.eval_batch_size)
eval_drop_remainder = True if FLAGS.use_tpu else False
eval_input_fn = file_based_input_fn_builder(
input_file=eval_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=eval_drop_remainder)
result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with open(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_predict:
pred_tags = []
true_tags = []
token_path = os.path.join(FLAGS.output_dir, "token_test.txt")
label_file = os.path.join(FLAGS.output_dir, "label2id.pkl")
label_masks = []
with open(label_file, "rb") as rf:
label2id = pickle.load(rf)
id2label = {value: key for key, value in label2id.items()}
if os.path.exists(token_path):
os.remove(token_path)
predict_examples = processor.get_test_examples(FLAGS.data_dir)
ground_truth_file = os.path.join(FLAGS.output_dir, "ground_truth.txt")
with open(ground_truth_file, 'w') as writer:
for ex_index, example in enumerate(predict_examples):
feature = convert_single_example(ex_index, example, label_list, FLAGS.max_seq_length, tokenizer, FLAGS.output_dir, "test")
line = []
for i, id in enumerate(feature.label_ids):
if feature.label_mask[i] == 1:
line.append(id2label[id])
true_tags.append(id2label[id])
# output_line = " ".join(id2label[id] for id in feature.label_ids if id != 0) + "\n"
output_line = " ".join(line) + "\n"
writer.write(output_line)
label_masks.append(feature.label_mask)
predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
file_based_convert_examples_to_features(predict_examples, label_list,
FLAGS.max_seq_length, tokenizer,
predict_file, FLAGS.output_dir, mode="test")
tf.logging.info("***** Running prediction*****")
tf.logging.info(" Num examples = %d", len(predict_examples))
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
if FLAGS.use_tpu:
# Warning: According to tpu_estimator.py Prediction on TPU is an
# experimental feature and hence not supported here
raise ValueError("Prediction in TPU not supported")
predict_drop_remainder = True if FLAGS.use_tpu else False
predict_input_fn = file_based_input_fn_builder(
input_file=predict_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=predict_drop_remainder)
result = estimator.predict(input_fn=predict_input_fn)
output_predict_file = os.path.join(FLAGS.output_dir, "label_test.txt")
with open(output_predict_file, 'w') as writer:
for i, prediction in enumerate(result):
line = []
for j, x in enumerate(prediction):
if label_masks[i][j] == 0:
continue
else:
line.append(id2label[x])
# writer.write(id2label[x] + "\n")
pred_tags.append(id2label[x])
output_line = " ".join(line) + "\n"
# # output_line = " ".join(id2label[id] for id in prediction if id != 0) + "\n"
writer.write(output_line)
# evaluate(true_tags, pred_tags, verbose=True)
# evaluate(true_tags, pred_tags)
tmp = codecs.open(os.path.join(FLAGS.output_dir, "tmp"), 'w', 'utf8')
with codecs.open(ground_truth_file, 'r', 'utf8') as ft, codecs.open(output_predict_file, 'r', 'utf8') as fg:
for lt, lg in zip(ft, fg):
for tl, tg in zip(lt.strip().split(), lg.strip().split()):
print('\t'.join([" ", tl, tg]), file=tmp)
tmp.close()
cmd = "python %s -d '\t' < %s > %s" % \
(os.path.join(os.getcwd(), "conlleval.py"), \
os.path.join(FLAGS.output_dir, "tmp"), \
os.path.join(FLAGS.data_dir, "test_results_ernie_base.txt"))
os.system(cmd)
if __name__ == "__main__":
flags.mark_flag_as_required("data_dir")
flags.mark_flag_as_required("task_name")
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| 33,809 | 39.011834 | 227 | py |
CLUE | CLUE-master/baselines/models/ernie/tokenization_test.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
import tokenization
import six
import tensorflow as tf
class TokenizationTest(tf.test.TestCase):
def test_full_tokenizer(self):
vocab_tokens = [
"[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
"##ing", ","
]
with tempfile.NamedTemporaryFile(delete=False) as vocab_writer:
if six.PY2:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
else:
vocab_writer.write("".join(
[x + "\n" for x in vocab_tokens]).encode("utf-8"))
vocab_file = vocab_writer.name
tokenizer = tokenization.FullTokenizer(vocab_file)
os.unlink(vocab_file)
tokens = tokenizer.tokenize(u"UNwant\u00E9d,running")
self.assertAllEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"])
self.assertAllEqual(
tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9])
def test_chinese(self):
tokenizer = tokenization.BasicTokenizer()
self.assertAllEqual(
tokenizer.tokenize(u"ah\u535A\u63A8zz"),
[u"ah", u"\u535A", u"\u63A8", u"zz"])
def test_basic_tokenizer_lower(self):
tokenizer = tokenization.BasicTokenizer(do_lower_case=True)
self.assertAllEqual(
tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "),
["hello", "!", "how", "are", "you", "?"])
self.assertAllEqual(tokenizer.tokenize(u"H\u00E9llo"), ["hello"])
def test_basic_tokenizer_no_lower(self):
tokenizer = tokenization.BasicTokenizer(do_lower_case=False)
self.assertAllEqual(
tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "),
["HeLLo", "!", "how", "Are", "yoU", "?"])
def test_wordpiece_tokenizer(self):
vocab_tokens = [
"[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
"##ing"
]
vocab = {}
for (i, token) in enumerate(vocab_tokens):
vocab[token] = i
tokenizer = tokenization.WordpieceTokenizer(vocab=vocab)
self.assertAllEqual(tokenizer.tokenize(""), [])
self.assertAllEqual(
tokenizer.tokenize("unwanted running"),
["un", "##want", "##ed", "runn", "##ing"])
self.assertAllEqual(
tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"])
def test_convert_tokens_to_ids(self):
vocab_tokens = [
"[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
"##ing"
]
vocab = {}
for (i, token) in enumerate(vocab_tokens):
vocab[token] = i
self.assertAllEqual(
tokenization.convert_tokens_to_ids(
vocab, ["un", "##want", "##ed", "runn", "##ing"]), [7, 4, 5, 8, 9])
def test_is_whitespace(self):
self.assertTrue(tokenization._is_whitespace(u" "))
self.assertTrue(tokenization._is_whitespace(u"\t"))
self.assertTrue(tokenization._is_whitespace(u"\r"))
self.assertTrue(tokenization._is_whitespace(u"\n"))
self.assertTrue(tokenization._is_whitespace(u"\u00A0"))
self.assertFalse(tokenization._is_whitespace(u"A"))
self.assertFalse(tokenization._is_whitespace(u"-"))
def test_is_control(self):
self.assertTrue(tokenization._is_control(u"\u0005"))
self.assertFalse(tokenization._is_control(u"A"))
self.assertFalse(tokenization._is_control(u" "))
self.assertFalse(tokenization._is_control(u"\t"))
self.assertFalse(tokenization._is_control(u"\r"))
self.assertFalse(tokenization._is_control(u"\U0001F4A9"))
def test_is_punctuation(self):
self.assertTrue(tokenization._is_punctuation(u"-"))
self.assertTrue(tokenization._is_punctuation(u"$"))
self.assertTrue(tokenization._is_punctuation(u"`"))
self.assertTrue(tokenization._is_punctuation(u"."))
self.assertFalse(tokenization._is_punctuation(u"A"))
self.assertFalse(tokenization._is_punctuation(u" "))
if __name__ == "__main__":
tf.test.main()
| 4,589 | 32.26087 | 80 | py |
CLUE | CLUE-master/baselines/models/ernie/run_pretraining.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run masked LM/next sentence masked_lm pre-training for BERT."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import modeling
import optimization
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_string(
"input_file", None,
"Input TF example files (can be a glob or comma separated).")
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written.")
## Other parameters
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_integer(
"max_seq_length", 128,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded. Must match data generation.")
flags.DEFINE_integer(
"max_predictions_per_seq", 20,
"Maximum number of masked LM predictions per sequence. "
"Must match data generation.")
flags.DEFINE_bool("do_train", False, "Whether to run training.")
flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
flags.DEFINE_integer("num_train_steps", 100000, "Number of training steps.")
flags.DEFINE_integer("num_warmup_steps", 10000, "Number of warmup steps.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_integer("max_eval_steps", 100, "Maximum number of eval steps.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
tf.flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
tf.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
def model_fn_builder(bert_config, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
masked_lm_positions = features["masked_lm_positions"]
masked_lm_ids = features["masked_lm_ids"]
masked_lm_weights = features["masked_lm_weights"]
next_sentence_labels = features["next_sentence_labels"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
(masked_lm_loss,
masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output(
bert_config, model.get_sequence_output(), model.get_embedding_table(),
masked_lm_positions, masked_lm_ids, masked_lm_weights)
(next_sentence_loss, next_sentence_example_loss,
next_sentence_log_probs) = get_next_sentence_output(
bert_config, model.get_pooled_output(), next_sentence_labels)
total_loss = masked_lm_loss + next_sentence_loss
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
masked_lm_weights, next_sentence_example_loss,
next_sentence_log_probs, next_sentence_labels):
"""Computes the loss and accuracy of the model."""
masked_lm_log_probs = tf.reshape(masked_lm_log_probs,
[-1, masked_lm_log_probs.shape[-1]])
masked_lm_predictions = tf.argmax(
masked_lm_log_probs, axis=-1, output_type=tf.int32)
masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
masked_lm_accuracy = tf.metrics.accuracy(
labels=masked_lm_ids,
predictions=masked_lm_predictions,
weights=masked_lm_weights)
masked_lm_mean_loss = tf.metrics.mean(
values=masked_lm_example_loss, weights=masked_lm_weights)
next_sentence_log_probs = tf.reshape(
next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
next_sentence_predictions = tf.argmax(
next_sentence_log_probs, axis=-1, output_type=tf.int32)
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
labels=next_sentence_labels, predictions=next_sentence_predictions)
next_sentence_mean_loss = tf.metrics.mean(
values=next_sentence_example_loss)
return {
"masked_lm_accuracy": masked_lm_accuracy,
"masked_lm_loss": masked_lm_mean_loss,
"next_sentence_accuracy": next_sentence_accuracy,
"next_sentence_loss": next_sentence_mean_loss,
}
eval_metrics = (metric_fn, [
masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
masked_lm_weights, next_sentence_example_loss,
next_sentence_log_probs, next_sentence_labels
])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode))
return output_spec
return model_fn
def get_masked_lm_output(bert_config, input_tensor, output_weights, positions,
label_ids, label_weights):
"""Get loss and log probs for the masked LM."""
input_tensor = gather_indexes(input_tensor, positions)
with tf.variable_scope("cls/predictions"):
# We apply one more non-linear transformation before the output layer.
# This matrix is not used after pre-training.
with tf.variable_scope("transform"):
input_tensor = tf.layers.dense(
input_tensor,
units=bert_config.hidden_size,
activation=modeling.get_activation(bert_config.hidden_act),
kernel_initializer=modeling.create_initializer(
bert_config.initializer_range))
input_tensor = modeling.layer_norm(input_tensor)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
output_bias = tf.get_variable(
"output_bias",
shape=[bert_config.vocab_size],
initializer=tf.zeros_initializer())
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
label_ids = tf.reshape(label_ids, [-1])
label_weights = tf.reshape(label_weights, [-1])
one_hot_labels = tf.one_hot(
label_ids, depth=bert_config.vocab_size, dtype=tf.float32)
# The `positions` tensor might be zero-padded (if the sequence is too
# short to have the maximum number of predictions). The `label_weights`
# tensor has a value of 1.0 for every real prediction and 0.0 for the
# padding predictions.
per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1])
numerator = tf.reduce_sum(label_weights * per_example_loss)
denominator = tf.reduce_sum(label_weights) + 1e-5
loss = numerator / denominator
return (loss, per_example_loss, log_probs)
def get_next_sentence_output(bert_config, input_tensor, labels):
"""Get loss and log probs for the next sentence prediction."""
# Simple binary classification. Note that 0 is "next sentence" and 1 is
# "random sentence". This weight matrix is not used after pre-training.
with tf.variable_scope("cls/seq_relationship"):
output_weights = tf.get_variable(
"output_weights",
shape=[2, bert_config.hidden_size],
initializer=modeling.create_initializer(bert_config.initializer_range))
output_bias = tf.get_variable(
"output_bias", shape=[2], initializer=tf.zeros_initializer())
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
labels = tf.reshape(labels, [-1])
one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, log_probs)
def gather_indexes(sequence_tensor, positions):
"""Gathers the vectors at the specific positions over a minibatch."""
sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3)
batch_size = sequence_shape[0]
seq_length = sequence_shape[1]
width = sequence_shape[2]
flat_offsets = tf.reshape(
tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])
flat_positions = tf.reshape(positions + flat_offsets, [-1])
flat_sequence_tensor = tf.reshape(sequence_tensor,
[batch_size * seq_length, width])
output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
return output_tensor
def input_fn_builder(input_files,
max_seq_length,
max_predictions_per_seq,
is_training,
num_cpu_threads=4):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
name_to_features = {
"input_ids":
tf.FixedLenFeature([max_seq_length], tf.int64),
"input_mask":
tf.FixedLenFeature([max_seq_length], tf.int64),
"segment_ids":
tf.FixedLenFeature([max_seq_length], tf.int64),
"masked_lm_positions":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_ids":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_weights":
tf.FixedLenFeature([max_predictions_per_seq], tf.float32),
"next_sentence_labels":
tf.FixedLenFeature([1], tf.int64),
}
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
if is_training:
d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
d = d.repeat()
d = d.shuffle(buffer_size=len(input_files))
# `cycle_length` is the number of parallel files that get read.
cycle_length = min(num_cpu_threads, len(input_files))
# `sloppy` mode means that the interleaving is not exact. This adds
# even more randomness to the training pipeline.
d = d.apply(
tf.contrib.data.parallel_interleave(
tf.data.TFRecordDataset,
sloppy=is_training,
cycle_length=cycle_length))
d = d.shuffle(buffer_size=100)
else:
d = tf.data.TFRecordDataset(input_files)
# Since we evaluate for a fixed number of steps we don't want to encounter
# out-of-range exceptions.
d = d.repeat()
# We must `drop_remainder` on training because the TPU requires fixed
# size dimensions. For eval, we assume we are evaluating on the CPU or GPU
# and we *don't* want to drop the remainder, otherwise we wont cover
# every sample.
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
num_parallel_batches=num_cpu_threads,
drop_remainder=True))
return d
return input_fn
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
if not FLAGS.do_train and not FLAGS.do_eval:
raise ValueError("At least one of `do_train` or `do_eval` must be True.")
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
tf.gfile.MakeDirs(FLAGS.output_dir)
input_files = []
for input_pattern in FLAGS.input_file.split(","):
input_files.extend(tf.gfile.Glob(input_pattern))
tf.logging.info("*** Input Files ***")
for input_file in input_files:
tf.logging.info(" %s" % input_file)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
model_fn = model_fn_builder(
bert_config=bert_config,
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=FLAGS.num_train_steps,
num_warmup_steps=FLAGS.num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size)
if FLAGS.do_train:
tf.logging.info("***** Running training *****")
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
train_input_fn = input_fn_builder(
input_files=input_files,
max_seq_length=FLAGS.max_seq_length,
max_predictions_per_seq=FLAGS.max_predictions_per_seq,
is_training=True)
estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps)
if FLAGS.do_eval:
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
eval_input_fn = input_fn_builder(
input_files=input_files,
max_seq_length=FLAGS.max_seq_length,
max_predictions_per_seq=FLAGS.max_predictions_per_seq,
is_training=False)
result = estimator.evaluate(
input_fn=eval_input_fn, steps=FLAGS.max_eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if __name__ == "__main__":
flags.mark_flag_as_required("input_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| 18,667 | 36.789474 | 82 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.