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
3DTrans
3DTrans-master/pcdet/ops/pointnet2/pointnet2_batch/__init__.py
0
0
0
py
3DTrans
3DTrans-master/pcdet/ops/pointnet2/pointnet2_batch/pointnet2_modules.py
from typing import List import torch import torch.nn as nn import torch.nn.functional as F from . import pointnet2_utils class _PointnetSAModuleBase(nn.Module): def __init__(self): super().__init__() self.npoint = None self.groupers = None self.mlps = None self.pool_method = 'max_pool' def calc_square_dist(self, a, b, norm=True): """ Calculating square distance between a and b a: [bs, n, c] b: [bs, m, c] """ n = a.shape[1] m = b.shape[1] num_channel = a.shape[-1] a_square = a.unsqueeze(dim=2) # [bs, n, 1, c] b_square = b.unsqueeze(dim=1) # [bs, 1, m, c] a_square = torch.sum(a_square * a_square, dim=-1) # [bs, n, 1] b_square = torch.sum(b_square * b_square, dim=-1) # [bs, 1, m] a_square = a_square.repeat((1, 1, m)) # [bs, n, m] b_square = b_square.repeat((1, n, 1)) # [bs, n, m] coor = torch.matmul(a, b.transpose(1, 2)) # [bs, n, m] if norm: dist = a_square + b_square - 2.0 * coor # [bs, npoint, ndataset] # dist = torch.sqrt(dist) else: dist = a_square + b_square - 2 * coor # dist = torch.sqrt(dist) return dist def forward(self, xyz: torch.Tensor, features: torch.Tensor = None, new_xyz=None) -> (torch.Tensor, torch.Tensor): """ :param xyz: (B, N, 3) tensor of the xyz coordinates of the features :param features: (B, N, C) tensor of the descriptors of the the features :param new_xyz: :return: new_xyz: (B, npoint, 3) tensor of the new features' xyz new_features: (B, npoint, \sum_k(mlps[k][-1])) tensor of the new_features descriptors """ new_features_list = [] xyz_flipped = xyz.transpose(1, 2).contiguous() if new_xyz is None: new_xyz = pointnet2_utils.gather_operation( xyz_flipped, pointnet2_utils.farthest_point_sample(xyz, self.npoint) ).transpose(1, 2).contiguous() if self.npoint is not None else None for i in range(len(self.groupers)): new_features = self.groupers[i](xyz, new_xyz, features) # (B, C, npoint, nsample) new_features = self.mlps[i](new_features) # (B, mlp[-1], npoint, nsample) if self.pool_method == 'max_pool': new_features = F.max_pool2d( new_features, kernel_size=[1, new_features.size(3)] ) # (B, mlp[-1], npoint, 1) elif self.pool_method == 'avg_pool': new_features = F.avg_pool2d( new_features, kernel_size=[1, new_features.size(3)] ) # (B, mlp[-1], npoint, 1) else: raise NotImplementedError new_features = new_features.squeeze(-1) # (B, mlp[-1], npoint) new_features_list.append(new_features) return new_xyz, torch.cat(new_features_list, dim=1) class PointnetSAModuleMSG(_PointnetSAModuleBase): """Pointnet set abstraction layer with multiscale grouping""" def __init__(self, *, npoint: int, radii: List[float], nsamples: List[int], mlps: List[List[int]], bn: bool = True, use_xyz: bool = True, pool_method='max_pool'): """ :param npoint: int :param radii: list of float, list of radii to group with :param nsamples: list of int, number of samples in each ball query :param mlps: list of list of int, spec of the pointnet before the global pooling for each scale :param bn: whether to use batchnorm :param use_xyz: :param pool_method: max_pool / avg_pool """ super().__init__() assert len(radii) == len(nsamples) == len(mlps) self.npoint = npoint self.groupers = nn.ModuleList() self.mlps = nn.ModuleList() for i in range(len(radii)): radius = radii[i] nsample = nsamples[i] self.groupers.append( pointnet2_utils.QueryAndGroup(radius, nsample, use_xyz=use_xyz) if npoint is not None else pointnet2_utils.GroupAll(use_xyz) ) mlp_spec = mlps[i] if use_xyz: mlp_spec[0] += 3 shared_mlps = [] for k in range(len(mlp_spec) - 1): shared_mlps.extend([ nn.Conv2d(mlp_spec[k], mlp_spec[k + 1], kernel_size=1, bias=False), nn.BatchNorm2d(mlp_spec[k + 1]), nn.ReLU() ]) self.mlps.append(nn.Sequential(*shared_mlps)) self.pool_method = pool_method class PointnetSAModuleMSG_WithSampling(_PointnetSAModuleBase): """Pointnet set abstraction layer with specific downsampling and multiscale grouping """ def __init__(self, *, npoint_list: List[int], sample_range_list: List[int], sample_type_list: List[int], radii: List[float], nsamples: List[int], mlps: List[List[int]], use_xyz: bool = True, dilated_group=False, pool_method='max_pool', aggregation_mlp: List[int], confidence_mlp: List[int], num_class): """ :param npoint_list: list of int, number of samples for every sampling type :param sample_range_list: list of list of int, sample index range [left, right] for every sampling type :param sample_type_list: list of str, list of used sampling type, d-fps or f-fps :param radii: list of float, list of radii to group with :param nsamples: list of int, number of samples in each ball query :param mlps: list of list of int, spec of the pointnet before the global pooling for each scale :param use_xyz: :param pool_method: max_pool / avg_pool :param dilated_group: whether to use dilated group :param aggregation_mlp: list of int, spec aggregation mlp :param confidence_mlp: list of int, spec confidence mlp :param num_class: int, class for process """ super().__init__() self.sample_type_list = sample_type_list self.sample_range_list = sample_range_list self.dilated_group = dilated_group assert len(radii) == len(nsamples) == len(mlps) self.npoint_list = npoint_list self.groupers = nn.ModuleList() self.mlps = nn.ModuleList() out_channels = 0 for i in range(len(radii)): radius = radii[i] nsample = nsamples[i] if self.dilated_group: if i == 0: min_radius = 0. else: min_radius = radii[i-1] self.groupers.append( pointnet2_utils.QueryDilatedAndGroup( radius, min_radius, nsample, use_xyz=use_xyz) if npoint_list is not None else pointnet2_utils.GroupAll(use_xyz) ) else: self.groupers.append( pointnet2_utils.QueryAndGroup( radius, nsample, use_xyz=use_xyz) if npoint_list is not None else pointnet2_utils.GroupAll(use_xyz) ) mlp_spec = mlps[i] if use_xyz: mlp_spec[0] += 3 shared_mlps = [] for k in range(len(mlp_spec) - 1): shared_mlps.extend([ nn.Conv2d(mlp_spec[k], mlp_spec[k + 1], kernel_size=1, bias=False), nn.BatchNorm2d(mlp_spec[k + 1]), nn.ReLU() ]) self.mlps.append(nn.Sequential(*shared_mlps)) out_channels += mlp_spec[-1] self.pool_method = pool_method if (aggregation_mlp is not None) and (len(aggregation_mlp) != 0) and (len(self.mlps) > 0): shared_mlp = [] for k in range(len(aggregation_mlp)): shared_mlp.extend([ nn.Conv1d(out_channels, aggregation_mlp[k], kernel_size=1, bias=False), nn.BatchNorm1d(aggregation_mlp[k]), nn.ReLU() ]) out_channels = aggregation_mlp[k] self.aggregation_layer = nn.Sequential(*shared_mlp) else: self.aggregation_layer = None if (confidence_mlp is not None) and (len(confidence_mlp) != 0): shared_mlp = [] for k in range(len(confidence_mlp)): shared_mlp.extend([ nn.Conv1d(out_channels, confidence_mlp[k], kernel_size=1, bias=False), nn.BatchNorm1d(confidence_mlp[k]), nn.ReLU() ]) out_channels = confidence_mlp[k] shared_mlp.append( nn.Conv1d(out_channels, num_class, kernel_size=1, bias=True), ) self.confidence_layers = nn.Sequential(*shared_mlp) else: self.confidence_layers = None def forward(self, xyz: torch.Tensor, features: torch.Tensor = None, cls_features: torch.Tensor = None, new_xyz=None, ctr_xyz=None): """ :param xyz: (B, N, 3) tensor of the xyz coordinates of the features :param features: (B, C, N) tensor of the descriptors of the the features :param cls_features: (B, N, num_class) tensor of the descriptors of the the confidence (classification) features :param new_xyz: (B, M, 3) tensor of the xyz coordinates of the sampled points "param ctr_xyz: tensor of the xyz coordinates of the centers :return: new_xyz: (B, npoint, 3) tensor of the new features' xyz new_features: (B, \sum_k(mlps[k][-1]), npoint) tensor of the new_features descriptors cls_features: (B, npoint, num_class) tensor of confidence (classification) features """ new_features_list = [] xyz_flipped = xyz.transpose(1, 2).contiguous() sampled_idx_list = [] if ctr_xyz is None: last_sample_end_index = 0 for i in range(len(self.sample_type_list)): sample_type = self.sample_type_list[i] sample_range = self.sample_range_list[i] npoint = self.npoint_list[i] if npoint <= 0: continue if sample_range == -1: #全部 xyz_tmp = xyz[:, last_sample_end_index:, :] feature_tmp = features.transpose(1, 2)[:, last_sample_end_index:, :].contiguous() cls_features_tmp = cls_features[:, last_sample_end_index:, :] if cls_features is not None else None else: xyz_tmp = xyz[:, last_sample_end_index:sample_range, :].contiguous() feature_tmp = features.transpose(1, 2)[:, last_sample_end_index:sample_range, :] cls_features_tmp = cls_features[:, last_sample_end_index:sample_range, :] if cls_features is not None else None last_sample_end_index += sample_range if xyz_tmp.shape[1] <= npoint: # No downsampling sample_idx = torch.arange(xyz_tmp.shape[1], device=xyz_tmp.device, dtype=torch.int32) * torch.ones(xyz_tmp.shape[0], xyz_tmp.shape[1], device=xyz_tmp.device, dtype=torch.int32) elif ('cls' in sample_type) or ('ctr' in sample_type): cls_features_max, class_pred = cls_features_tmp.max(dim=-1) score_pred = torch.sigmoid(cls_features_max) # B,N score_picked, sample_idx = torch.topk(score_pred, npoint, dim=-1) sample_idx = sample_idx.int() elif 'D-FPS' in sample_type or 'DFS' in sample_type: sample_idx = pointnet2_utils.furthest_point_sample(xyz_tmp.contiguous(), npoint) elif 'F-FPS' in sample_type or 'FFS' in sample_type: features_SSD = torch.cat([xyz_tmp, feature_tmp], dim=-1) features_for_fps_distance = self.calc_square_dist(features_SSD, features_SSD) features_for_fps_distance = features_for_fps_distance.contiguous() sample_idx = pointnet2_utils.furthest_point_sample_with_dist(features_for_fps_distance, npoint) elif sample_type == 'FS': features_SSD = torch.cat([xyz_tmp, feature_tmp], dim=-1) features_for_fps_distance = self.calc_square_dist(features_SSD, features_SSD) features_for_fps_distance = features_for_fps_distance.contiguous() sample_idx_1 = pointnet2_utils.furthest_point_sample_with_dist(features_for_fps_distance, npoint) sample_idx_2 = pointnet2_utils.furthest_point_sample(xyz_tmp, npoint) sample_idx = torch.cat([sample_idx_1, sample_idx_2], dim=-1) # [bs, npoint * 2] elif 'Rand' in sample_type: sample_idx = torch.randperm(xyz_tmp.shape[1],device=xyz_tmp.device)[None, :npoint].int().repeat(xyz_tmp.shape[0], 1) elif sample_type == 'ds_FPS' or sample_type == 'ds-FPS': part_num = 4 xyz_div = [] idx_div = [] for i in range(len(xyz_tmp)): per_xyz = xyz_tmp[i] radii = per_xyz.norm(dim=-1) -5 storted_radii, indince = radii.sort(dim=0, descending=False) per_xyz_sorted = per_xyz[indince] per_xyz_sorted_div = per_xyz_sorted.view(part_num, -1 ,3) per_idx_div = indince.view(part_num,-1) xyz_div.append(per_xyz_sorted_div) idx_div.append(per_idx_div) xyz_div = torch.cat(xyz_div ,dim=0) idx_div = torch.cat(idx_div ,dim=0) idx_sampled = pointnet2_utils.furthest_point_sample(xyz_div, (npoint//part_num)) indince_div = [] for idx_sampled_per, idx_per in zip(idx_sampled, idx_div): indince_div.append(idx_per[idx_sampled_per.long()]) index = torch.cat(indince_div, dim=-1) sample_idx = index.reshape(xyz.shape[0], npoint).int() elif sample_type == 'ry_FPS' or sample_type == 'ry-FPS': part_num = 4 xyz_div = [] idx_div = [] for i in range(len(xyz_tmp)): per_xyz = xyz_tmp[i] ry = torch.atan(per_xyz[:,0]/per_xyz[:,1]) storted_ry, indince = ry.sort(dim=0, descending=False) per_xyz_sorted = per_xyz[indince] per_xyz_sorted_div = per_xyz_sorted.view(part_num, -1 ,3) per_idx_div = indince.view(part_num,-1) xyz_div.append(per_xyz_sorted_div) idx_div.append(per_idx_div) xyz_div = torch.cat(xyz_div ,dim=0) idx_div = torch.cat(idx_div ,dim=0) idx_sampled = pointnet2_utils.furthest_point_sample(xyz_div, (npoint//part_num)) indince_div = [] for idx_sampled_per, idx_per in zip(idx_sampled, idx_div): indince_div.append(idx_per[idx_sampled_per.long()]) index = torch.cat(indince_div, dim=-1) sample_idx = index.reshape(xyz.shape[0], npoint).int() sampled_idx_list.append(sample_idx) sampled_idx_list = torch.cat(sampled_idx_list, dim=-1) new_xyz = pointnet2_utils.gather_operation(xyz_flipped, sampled_idx_list).transpose(1, 2).contiguous() else: new_xyz = ctr_xyz if len(self.groupers) > 0: for i in range(len(self.groupers)): new_features = self.groupers[i](xyz, new_xyz, features) # (B, C, npoint, nsample) new_features = self.mlps[i](new_features) # (B, mlp[-1], npoint, nsample) if self.pool_method == 'max_pool': new_features = F.max_pool2d( new_features, kernel_size=[1, new_features.size(3)] ) # (B, mlp[-1], npoint, 1) elif self.pool_method == 'avg_pool': new_features = F.avg_pool2d( new_features, kernel_size=[1, new_features.size(3)] ) # (B, mlp[-1], npoint, 1) else: raise NotImplementedError new_features = new_features.squeeze(-1) # (B, mlp[-1], npoint) new_features_list.append(new_features) new_features = torch.cat(new_features_list, dim=1) if self.aggregation_layer is not None: new_features = self.aggregation_layer(new_features) else: new_features = pointnet2_utils.gather_operation(features, sampled_idx_list).contiguous() if self.confidence_layers is not None: cls_features = self.confidence_layers(new_features).transpose(1, 2) else: cls_features = None return new_xyz, new_features, cls_features class Vote_layer(nn.Module): """ Light voting module with limitation""" def __init__(self, mlp_list, pre_channel, max_translate_range): super().__init__() self.mlp_list = mlp_list if len(mlp_list) > 0: for i in range(len(mlp_list)): shared_mlps = [] shared_mlps.extend([ nn.Conv1d(pre_channel, mlp_list[i], kernel_size=1, bias=False), nn.BatchNorm1d(mlp_list[i]), nn.ReLU() ]) pre_channel = mlp_list[i] self.mlp_modules = nn.Sequential(*shared_mlps) else: self.mlp_modules = None self.ctr_reg = nn.Conv1d(pre_channel, 3, kernel_size=1) self.max_offset_limit = torch.tensor(max_translate_range).float() if max_translate_range is not None else None def forward(self, xyz, features): xyz_select = xyz features_select = features if self.mlp_modules is not None: new_features = self.mlp_modules(features_select) #([4, 256, 256]) ->([4, 128, 256]) else: new_features = new_features ctr_offsets = self.ctr_reg(new_features) #[4, 128, 256]) -> ([4, 3, 256]) ctr_offsets = ctr_offsets.transpose(1, 2)#([4, 256, 3]) feat_offets = ctr_offsets[..., 3:] new_features = feat_offets ctr_offsets = ctr_offsets[..., :3] if self.max_offset_limit is not None: max_offset_limit = self.max_offset_limit.view(1, 1, 3) max_offset_limit = self.max_offset_limit.repeat((xyz_select.shape[0], xyz_select.shape[1], 1)).to(xyz_select.device) #([4, 256, 3]) limited_ctr_offsets = torch.where(ctr_offsets > max_offset_limit, max_offset_limit, ctr_offsets) min_offset_limit = -1 * max_offset_limit limited_ctr_offsets = torch.where(limited_ctr_offsets < min_offset_limit, min_offset_limit, limited_ctr_offsets) vote_xyz = xyz_select + limited_ctr_offsets else: vote_xyz = xyz_select + ctr_offsets return vote_xyz, new_features, xyz_select, ctr_offsets class PointnetSAModule(PointnetSAModuleMSG): """Pointnet set abstraction layer""" def __init__(self, *, mlp: List[int], npoint: int = None, radius: float = None, nsample: int = None, bn: bool = True, use_xyz: bool = True, pool_method='max_pool'): """ :param mlp: list of int, spec of the pointnet before the global max_pool :param npoint: int, number of features :param radius: float, radius of ball :param nsample: int, number of samples in the ball query :param bn: whether to use batchnorm :param use_xyz: :param pool_method: max_pool / avg_pool """ super().__init__( mlps=[mlp], npoint=npoint, radii=[radius], nsamples=[nsample], bn=bn, use_xyz=use_xyz, pool_method=pool_method ) class PointnetFPModule(nn.Module): r"""Propigates the features of one set to another""" def __init__(self, *, mlp: List[int], bn: bool = True): """ :param mlp: list of int :param bn: whether to use batchnorm """ super().__init__() shared_mlps = [] for k in range(len(mlp) - 1): shared_mlps.extend([ nn.Conv2d(mlp[k], mlp[k + 1], kernel_size=1, bias=False), nn.BatchNorm2d(mlp[k + 1]), nn.ReLU() ]) self.mlp = nn.Sequential(*shared_mlps) def forward( self, unknown: torch.Tensor, known: torch.Tensor, unknow_feats: torch.Tensor, known_feats: torch.Tensor ) -> torch.Tensor: """ :param unknown: (B, n, 3) tensor of the xyz positions of the unknown features :param known: (B, m, 3) tensor of the xyz positions of the known features :param unknow_feats: (B, C1, n) tensor of the features to be propigated to :param known_feats: (B, C2, m) tensor of features to be propigated :return: new_features: (B, mlp[-1], n) tensor of the features of the unknown features """ if known is not None: dist, idx = pointnet2_utils.three_nn(unknown, known) dist_recip = 1.0 / (dist + 1e-8) norm = torch.sum(dist_recip, dim=2, keepdim=True) weight = dist_recip / norm interpolated_feats = pointnet2_utils.three_interpolate(known_feats, idx, weight) else: interpolated_feats = known_feats.expand(*known_feats.size()[0:2], unknown.size(1)) if unknow_feats is not None: new_features = torch.cat([interpolated_feats, unknow_feats], dim=1) # (B, C2 + C1, n) else: new_features = interpolated_feats new_features = new_features.unsqueeze(-1) new_features = self.mlp(new_features) return new_features.squeeze(-1) if __name__ == "__main__": pass
22,835
43.341748
196
py
3DTrans
3DTrans-master/pcdet/ops/iou3d_nms/iou3d_nms_utils.py
""" 3D IoU Calculation and Rotated NMS Written by Shaoshuai Shi All Rights Reserved 2019-2020. """ import torch from ...utils import common_utils from . import iou3d_nms_cuda def boxes_bev_iou_cpu(boxes_a, boxes_b): """ Args: boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading] boxes_b: (M, 7) [x, y, z, dx, dy, dz, heading] Returns: ans_iou: (N, M) """ boxes_a, is_numpy = common_utils.check_numpy_to_torch(boxes_a) boxes_b, is_numpy = common_utils.check_numpy_to_torch(boxes_b) assert not (boxes_a.is_cuda or boxes_b.is_cuda), 'Only support CPU tensors' assert boxes_a.shape[1] == 7 and boxes_b.shape[1] == 7 ans_iou = boxes_a.new_zeros(torch.Size((boxes_a.shape[0], boxes_b.shape[0]))) iou3d_nms_cuda.boxes_iou_bev_cpu(boxes_a.contiguous(), boxes_b.contiguous(), ans_iou) return ans_iou.numpy() if is_numpy else ans_iou def boxes_iou_bev(boxes_a, boxes_b): """ Args: boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading] boxes_b: (M, 7) [x, y, z, dx, dy, dz, heading] Returns: ans_iou: (N, M) """ assert boxes_a.shape[1] == boxes_b.shape[1] == 7 ans_iou = torch.cuda.FloatTensor(torch.Size((boxes_a.shape[0], boxes_b.shape[0]))).zero_() iou3d_nms_cuda.boxes_iou_bev_gpu(boxes_a.contiguous(), boxes_b.contiguous(), ans_iou) return ans_iou def boxes_iou3d_gpu(boxes_a, boxes_b): """ Args: boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading] boxes_b: (M, 7) [x, y, z, dx, dy, dz, heading] Returns: ans_iou: (N, M) """ assert boxes_a.shape[1] == boxes_b.shape[1] == 7 # height overlap boxes_a_height_max = (boxes_a[:, 2] + boxes_a[:, 5] / 2).view(-1, 1) boxes_a_height_min = (boxes_a[:, 2] - boxes_a[:, 5] / 2).view(-1, 1) boxes_b_height_max = (boxes_b[:, 2] + boxes_b[:, 5] / 2).view(1, -1) boxes_b_height_min = (boxes_b[:, 2] - boxes_b[:, 5] / 2).view(1, -1) # bev overlap overlaps_bev = torch.cuda.FloatTensor(torch.Size((boxes_a.shape[0], boxes_b.shape[0]))).zero_() # (N, M) iou3d_nms_cuda.boxes_overlap_bev_gpu(boxes_a.contiguous(), boxes_b.contiguous(), overlaps_bev) max_of_min = torch.max(boxes_a_height_min, boxes_b_height_min) min_of_max = torch.min(boxes_a_height_max, boxes_b_height_max) overlaps_h = torch.clamp(min_of_max - max_of_min, min=0) # 3d iou overlaps_3d = overlaps_bev * overlaps_h vol_a = (boxes_a[:, 3] * boxes_a[:, 4] * boxes_a[:, 5]).view(-1, 1) vol_b = (boxes_b[:, 3] * boxes_b[:, 4] * boxes_b[:, 5]).view(1, -1) iou3d = overlaps_3d / torch.clamp(vol_a + vol_b - overlaps_3d, min=1e-6) return iou3d def nms_gpu(boxes, scores, thresh, pre_maxsize=None, **kwargs): """ :param boxes: (N, 7) [x, y, z, dx, dy, dz, heading] :param scores: (N) :param thresh: :return: """ assert boxes.shape[1] == 7 order = scores.sort(0, descending=True)[1] if pre_maxsize is not None: order = order[:pre_maxsize] boxes = boxes[order].contiguous() keep = torch.LongTensor(boxes.size(0)) num_out = iou3d_nms_cuda.nms_gpu(boxes, keep, thresh) return order[keep[:num_out].cuda()].contiguous(), None def nms_normal_gpu(boxes, scores, thresh, **kwargs): """ :param boxes: (N, 7) [x, y, z, dx, dy, dz, heading] :param scores: (N) :param thresh: :return: """ assert boxes.shape[1] == 7 order = scores.sort(0, descending=True)[1] boxes = boxes[order].contiguous() keep = torch.LongTensor(boxes.size(0)) num_out = iou3d_nms_cuda.nms_normal_gpu(boxes, keep, thresh) return order[keep[:num_out].cuda()].contiguous(), None
3,673
30.401709
109
py
3DTrans
3DTrans-master/pcdet/ops/iou3d_nms/__init__.py
0
0
0
py
3DTrans
3DTrans-master/pcdet/ops/roiaware_pool3d/__init__.py
0
0
0
py
3DTrans
3DTrans-master/pcdet/ops/roiaware_pool3d/roiaware_pool3d_utils.py
import torch import torch.nn as nn from torch.autograd import Function from ...utils import common_utils from . import roiaware_pool3d_cuda def points_in_boxes_cpu(points, boxes): """ Args: points: (num_points, 3) boxes: [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center, each box DO NOT overlaps Returns: point_indices: (N, num_points) """ assert boxes.shape[1] == 7 assert points.shape[1] == 3 points, is_numpy = common_utils.check_numpy_to_torch(points) boxes, is_numpy = common_utils.check_numpy_to_torch(boxes) point_indices = points.new_zeros((boxes.shape[0], points.shape[0]), dtype=torch.int) roiaware_pool3d_cuda.points_in_boxes_cpu(boxes.float().contiguous(), points.float().contiguous(), point_indices) return point_indices.numpy() if is_numpy else point_indices def points_in_boxes_gpu(points, boxes): """ :param points: (B, M, 3) :param boxes: (B, T, 7), num_valid_boxes <= T :return box_idxs_of_pts: (B, M), default background = -1 """ assert boxes.shape[0] == points.shape[0] assert boxes.shape[2] == 7 and points.shape[2] == 3 batch_size, num_points, _ = points.shape box_idxs_of_pts = points.new_zeros((batch_size, num_points), dtype=torch.int).fill_(-1) roiaware_pool3d_cuda.points_in_boxes_gpu(boxes.contiguous(), points.contiguous(), box_idxs_of_pts) return box_idxs_of_pts class RoIAwarePool3d(nn.Module): def __init__(self, out_size, max_pts_each_voxel=128): super().__init__() self.out_size = out_size self.max_pts_each_voxel = max_pts_each_voxel def forward(self, rois, pts, pts_feature, pool_method='max'): assert pool_method in ['max', 'avg'] return RoIAwarePool3dFunction.apply(rois, pts, pts_feature, self.out_size, self.max_pts_each_voxel, pool_method) class RoIAwarePool3dFunction(Function): @staticmethod def forward(ctx, rois, pts, pts_feature, out_size, max_pts_each_voxel, pool_method): """ Args: ctx: rois: (N, 7) [x, y, z, dx, dy, dz, heading] (x, y, z) is the box center pts: (npoints, 3) pts_feature: (npoints, C) out_size: int or tuple, like 7 or (7, 7, 7) max_pts_each_voxel: pool_method: 'max' or 'avg' Returns: pooled_features: (N, out_x, out_y, out_z, C) """ assert rois.shape[1] == 7 and pts.shape[1] == 3 if isinstance(out_size, int): out_x = out_y = out_z = out_size else: assert len(out_size) == 3 for k in range(3): assert isinstance(out_size[k], int) out_x, out_y, out_z = out_size num_rois = rois.shape[0] num_channels = pts_feature.shape[-1] num_pts = pts.shape[0] pooled_features = pts_feature.new_zeros((num_rois, out_x, out_y, out_z, num_channels)) argmax = pts_feature.new_zeros((num_rois, out_x, out_y, out_z, num_channels), dtype=torch.int) pts_idx_of_voxels = pts_feature.new_zeros((num_rois, out_x, out_y, out_z, max_pts_each_voxel), dtype=torch.int) pool_method_map = {'max': 0, 'avg': 1} pool_method = pool_method_map[pool_method] roiaware_pool3d_cuda.forward(rois, pts, pts_feature, argmax, pts_idx_of_voxels, pooled_features, pool_method) ctx.roiaware_pool3d_for_backward = (pts_idx_of_voxels, argmax, pool_method, num_pts, num_channels) return pooled_features @staticmethod def backward(ctx, grad_out): """ :param grad_out: (N, out_x, out_y, out_z, C) :return: grad_in: (npoints, C) """ pts_idx_of_voxels, argmax, pool_method, num_pts, num_channels = ctx.roiaware_pool3d_for_backward grad_in = grad_out.new_zeros((num_pts, num_channels)) roiaware_pool3d_cuda.backward(pts_idx_of_voxels, argmax, grad_out.contiguous(), grad_in, pool_method) return None, None, grad_in, None, None, None if __name__ == '__main__': pass
4,075
35.392857
120
py
caringcaribou
caringcaribou-master/setup.py
#!/usr/bin/env python """ Caring Caribou ============== - A friendly automotive security exploration tool, initiated as part of the research project HEAVENS (HEAling Vulnerabilities to ENhance Software Security and Safety), now a stand-alone project. - A zero-knowledge tool that can be dropped onto an automotive network and collect information regarding what services and vulnerabilities exist. """ from setuptools import find_packages, setup version = "0.4" dl_version = "master" if "dev" in version else "v{}".format(version) print(r"""----------------------------------- Installing Caring Caribou version {0} ----------------------------------- """.format(version)) setup( name="caringcaribou", version=version, author="Kasper Karlsson", # author_email="TBD", description="A friendly automotive security exploration tool", long_description=__doc__, keywords=["automotive", "security", "CAN", "automotive protocols", "fuzzing"], url="https://github.com/CaringCaribou/caringcaribou/", download_url="https://github.com/CaringCaribou/caringcaribou/tarball/{}".format(dl_version), license="GPLv3", packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ "python-can" ], entry_points={ "console_scripts": [ "cc.py=caringcaribou.caringcaribou:main", "caringcaribou=caringcaribou.caringcaribou:main", ], "caringcaribou.modules": [ "dcm = caringcaribou.modules.dcm", "doip = caringcaribou.modules.doip", "dump = caringcaribou.modules.dump", "fuzzer = caringcaribou.modules.fuzzer", "listener = caringcaribou.modules.listener", "send = caringcaribou.modules.send", "test = caringcaribou.modules.test", "uds_fuzz = caringcaribou.modules.uds_fuzz", "uds = caringcaribou.modules.uds", "xcp = caringcaribou.modules.xcp", ] } ) print(r"""----------------------------------------------------------- Installation completed, run `cc.py --help` to get started ----------------------------------------------------------- """)
2,202
35.716667
194
py
caringcaribou
caringcaribou-master/caringcaribou/caringcaribou.py
#!/usr/bin/env python # Released under GNU General Public License v3 # https://github.com/CaringCaribou/caringcaribou import argparse import can import errno from .utils import can_actions import traceback import pkg_resources VERSION = "0.4" def show_script_header(): """Show script header""" print(r""" {0} CARING CARIBOU v{1} {0} """.format("-"*(16 + len(VERSION)), VERSION)) def fancy_header(): """ Returns a fancy header string. :rtype: str """ return r"""{0} CARING CARIBOU v{1} \_\_ _/_/ \__/ (oo)\_______ (__)\ )\/ ||-----|| || || {0} """.format("-"*(16 + len(VERSION)), VERSION) def available_modules_dict(): available_modules = dict() for entry_point in pkg_resources.iter_entry_points("caringcaribou.modules"): nicename = str(entry_point).split("=")[0].strip() available_modules[nicename] = entry_point return available_modules def available_modules(): """ Get a string showing available CaringCaribou modules. Modules are listed in setup.py: entry_points['caringcaribou.modules'] :return: A string listing available modules :rtype: str """ modules = list(available_modules_dict().keys()) modules.sort() mod_str = "available modules:\n " mod_str += ", ".join(modules) return mod_str def parse_arguments(): """ Argument parser for interface, module name and module arguments. :return: Namespace containing module name and arguments :rtype: argparse.Namespace """ parser = argparse.ArgumentParser(description="{0}A friendly car security exploration tool".format(fancy_header()), formatter_class=argparse.RawDescriptionHelpFormatter, epilog=available_modules()) parser.add_argument("-i", dest="interface", default=None, help="force interface, e.g. 'can1' or 'vcan0'") parser.add_argument("module", help="Name of the module to run") parser.add_argument("module_args", metavar="...", nargs=argparse.REMAINDER, help="Arguments to module") args = parser.parse_args() return args def load_module(module_name): """ Dynamically imports module_name from the folder specified by MODULES_DIR. :param str module_name: Name of the module to import as referenced in entry_points e.g. "dcm", "uds", "listener" :return: a module on success, None otherwise """ try: print("Loading module '{0}'\n".format(module_name)) cc_mod = available_modules_dict()[module_name] return cc_mod except KeyError as e: print("Load module failed: module {0} is not available".format(e)) return None def main(): """Main execution handler""" # Parse and validate arguments args = parse_arguments() # Show header show_script_header() # Save interface to can_actions, for use in modules if args.interface: can_actions.DEFAULT_INTERFACE = args.interface try: # Load module cc_mod = load_module(args.module).load() cc_mod.module_main(args.module_args) except AttributeError as e: pass # Main wrapper if __name__ == '__main__': try: main() except KeyboardInterrupt: pass except can.CanError as e: print("\nCanError: {0}".format(e)) except IOError as e: if e.errno is errno.ENODEV: # Specifically catch "[Errno 19] No such device", which is caused by using an invalid interface print("\nIOError: {0}. This might be caused by an invalid or inactive CAN interface.".format(e)) else: # Print original stack trace traceback.print_exc() finally: print("")
3,864
27.007246
118
py
caringcaribou
caringcaribou-master/caringcaribou/__init__.py
0
0
0
py
caringcaribou
caringcaribou-master/caringcaribou/modules/test.py
from __future__ import print_function from caringcaribou.utils.can_actions import DEFAULT_INTERFACE import caringcaribou.tests import unittest def print_interface_header(): """Prints a header showing which interface is used""" interface_str = DEFAULT_INTERFACE if DEFAULT_INTERFACE is not None else "default" message = "Running tests using CAN interface '{0}'\n".format(interface_str) print(message) def module_main(_): """Runs all Caring Caribou unit tests""" print_interface_header() # Run tests test_suite = unittest.TestLoader().loadTestsFromModule(caringcaribou.tests) unittest.TextTestRunner(verbosity=2).run(test_suite)
667
32.4
85
py
caringcaribou
caringcaribou-master/caringcaribou/modules/dump.py
from __future__ import print_function from caringcaribou.utils.can_actions import CanActions from caringcaribou.utils.common import msg_to_candump_format, parse_int_dec_or_hex from caringcaribou.modules.send import FILE_LINE_COMMENT_PREFIX from sys import argv, stdout import argparse import datetime def initiate_dump(handler, whitelist, separator_seconds, candump_format): """ Runs the 'handler' function on all incoming CAN messages. Filtering is controlled by the list 'args.whitelist' A separator is printed between messages if no messages have been handled in float 'args.separator_seconds' :param handler: function to call on all incoming messages :param whitelist: list of allowed arbitration IDs, or None to allow all :param separator_seconds: float seconds before printing a separator between messages, or None to never do this :param candump_format: bool indicating whether messages should be passed to 'handler' in candump str format """ if candump_format: format_func = msg_to_candump_format else: format_func = str separator_enabled = separator_seconds is not None last_message_timestamp = datetime.datetime.min messages_since_last_separator = 0 print("Dumping CAN traffic (press Ctrl+C to exit)".format(whitelist)) with CanActions(notifier_enabled=False) as can_wrap: for msg in can_wrap.bus: # Separator handling if separator_enabled and messages_since_last_separator > 0: if (datetime.datetime.now() - last_message_timestamp).total_seconds() > separator_seconds: # Print separator handler("--- Count: {0}".format(messages_since_last_separator)) messages_since_last_separator = 0 # Message handling if len(whitelist) == 0 or msg.arbitration_id in whitelist: handler(format_func(msg)) last_message_timestamp = datetime.datetime.now() messages_since_last_separator += 1 def parse_args(args): """ Argument parser for the dump module. :param args: List of arguments :return: Argument namespace """ parser = argparse.ArgumentParser(prog="cc.py dump", formatter_class=argparse.RawDescriptionHelpFormatter, description="CAN traffic dump module for CaringCaribou", epilog="""Example usage: cc.py dump cc.py dump -s 1.0 cc.py dump -f output.txt cc.py dump -c -f output.txt 0x733 0x734""") parser.add_argument("-f", "--file", metavar="F", help="Write output to file F (default: stdout)") parser.add_argument("whitelist", type=parse_int_dec_or_hex, metavar="W", nargs="*", help="Arbitration ID to whitelist") parser.add_argument("-c", action="store_true", dest="candump_format", help="Output on candump format") parser.add_argument("-s", type=float, metavar="SEC", dest="separator_seconds", help="Print separating line after SEC silent seconds") args = parser.parse_args(args) return args def file_header(): """ Returns an output file header string, consisting of a number of comment lines. :return: str header """ argument_str = " ".join(argv) lines = ["Caring Caribou dump file", datetime.datetime.now(), argument_str] header = "".join(["{0} {1}\n".format(FILE_LINE_COMMENT_PREFIX, line) for line in lines]) return header def module_main(args): """ Dump module main wrapper. :param args: List of module arguments """ args = parse_args(args) separator_seconds = args.separator_seconds candump_format = args.candump_format whitelist = args.whitelist # Print to stdout if args.file is None: initiate_dump(print, whitelist, separator_seconds, candump_format) # Print to file else: try: with open(args.file, "w") as output_file: global count count = 0 # Write file header header = file_header() output_file.write(header) def write_line_to_file(line): global count count += 1 print("\rMessages printed to file: {0}".format(count), end="") output_file.write("{0}\n".format(line)) stdout.flush() initiate_dump(write_line_to_file, whitelist, separator_seconds, candump_format) except IOError as e: print("IOError: {0}".format(e))
4,952
36.522727
114
py
caringcaribou
caringcaribou-master/caringcaribou/modules/dcm.py
from __future__ import print_function from caringcaribou.utils.can_actions import CanActions from caringcaribou.utils.common import parse_int_dec_or_hex from sys import stdout import argparse import time DCM_SERVICE_NAMES = { 0x10: "DIAGNOSTIC_SESSION_CONTROL", 0x11: "ECU_RESET", 0x12: "GMLAN_READ_FAILURE_RECORD", 0x14: "CLEAR_DIAGNOSTIC_INFORMATION", 0x19: "READ_DTC_INFORMATION", 0x1A: "GMLAN_READ_DIAGNOSTIC_ID", 0x20: "RETURN_TO_NORMAL", 0x22: "READ_DATA_BY_IDENTIFIER", 0x23: "READ_MEMORY_BY_ADDRESS", 0x24: "READ_SCALING_DATA_BY_IDENTIFIER", 0x27: "SECURITY_ACCESS", 0x28: "COMMUNICATION_CONTROL", 0x2A: "READ_DATA_BY_PERIODIC_IDENTIFIER", 0x2C: "DYNAMICALLY_DEFINE_DATA_IDENTIFIER", 0x2D: "DEFINE_PID_BY_MEMORY_ADDRESS", 0x2E: "WRITE_DATA_BY_IDENTIFIER", 0x2F: "INPUT_OUTPUT_CONTROL_BY_IDENTIFIER", 0x31: "ROUTINE_CONTROL", 0x34: "REQUEST_DOWNLOAD", 0x35: "REQUEST_UPLOAD", 0x36: "TRANSFER_DATA", 0x37: "REQUEST_TRANSFER_EXIT", 0x38: "REQUEST_FILE_TRANSFER", 0x3B: "GMLAN_WRITE_DID", 0x3D: "WRITE_MEMORY_BY_ADDRESS", 0x3E: "TESTER_PRESENT", 0x7F: "NEGATIVE_RESPONSE", 0x83: "ACCESS_TIMING_PARAMETER", 0x84: "SECURED_DATA_TRANSMISSION", 0x85: "CONTROL_DTC_SETTING", 0x86: "RESPONSE_ON_EVENT", 0x87: "LINK_CONTROL", 0xA2: "GMLAN_REPORT_PROGRAMMING_STATE", 0xA5: "GMLAN_ENTER_PROGRAMMING_MODE", 0xA9: "GMLAN_CHECK_CODES", 0xAA: "GMLAN_READ_DPID", 0xAE: "GMLAN_DEVICE_CONTROL" } NRC = { 0x10: "generalReject", 0x11: "serviceNotSupported", 0x12: "sub-functionNotSupported", 0x13: "incorrectMessageLengthOrInvalidFormat", 0x14: "responseTooBig", 0x21: "busyRepeatRequest", 0x22: "conditionsNotCorrect", 0x24: "requestSequenceError", 0x25: "noResponseFromSub-netComponent", 0x26: "failurePreventsExecutionOfRequestedAction", 0x31: "requestOutOfRange", 0x33: "securityAccessDenied", 0x35: "invalidKey", 0x36: "exceededNumberOfAttempts", 0x37: "requiredTimeDelayNotExpired", 0x70: "uploadDownloadNotAccepted", 0x71: "transferDataSuspended", 0x72: "generalProgrammingFailure", 0x73: "wrongBlockSequenceCounter", 0x78: "requestCorrectlyReceivedResponsePending", 0x7E: "sub-FunctionNotSupportedInActiveSession", 0x7F: "serviceNotSupportedInActiveSession" } def insert_message_length(data, pad=False): """ Inserts a message length byte before data :param data: Message data :param pad: If True, pads returned data to 8 bytes :return: """ length = len(data) if length > 7: raise IndexError("Data can only contain up to 7 bytes: {0}".format(len(data))) full_data = [length] + data if pad: full_data += [0x00] * (7-length) return full_data def dcm_dtc(args): """ Fetches and prints the Diagnostic Trouble Codes from a supported service (Mode $03) :param args: A namespace containing src, dst and clear """ send_arb_id = args.src rcv_arb_id = args.dst clear = args.clear big_data = [] big_data_size = 0 def dtc_type(x): return { 0: "P", 1: "C", 2: "B", 3: "U", }.get(x, "?") def decode_dtc(data): # Expects 2 bytes if len(data) != 2: return return dtc_type((data[0] & 0xC0) >> 6) + format((data[0] & 0x30) >> 4) + format(data[0] & 0x0F, "01x") + format( data[1], "02x") def decode_dtc_pkt(msg): if msg.arbitration_id != rcv_arb_id: return return_packet = False # TODO: Are we sure that data byte 0 is 0x10, or should the check be against data[0] & 0x10 instead? if msg.data[0] == 0x10 and (msg.data[2] == 0x43 or msg.data[2] == 0x47): return_packet = True if (msg.data[0] & 0xF0) == 0x20: # We should probably set a state for this return_packet = True if msg.data[1] == 0x43: return_packet = True if msg.data[2] == 0x47: return_packet = True if not return_packet: return global big_data global big_data_size if big_data_size == 0 and (msg.data[1] == 0x43 or msg.data[1] == 0x47): # Single frame print("There are {0} DTCs".format(msg.data[2])) if msg.data[2] == 0: return if msg.data[0] > 2: print("DTC: {0}".format(decode_dtc(msg.data[3:5]))) if msg.data[0] > 4: print("DTC: {0}".format(decode_dtc(msg.data[5:6]))) if msg.data[0] > 6: print("DTC: {0}".format(decode_dtc(msg.data[7:9]))) if msg.data[0] == 0x10: # Multi Frame (First Frame) full_dlc = (msg.data[0] & 0x0F) + msg.data[1] print("There are {0} DTCs".format(msg.data[3])) print("DTC: {0}".format(decode_dtc(msg.data[4:6]))) print("DTC: {0}".format(decode_dtc(msg.data[6:8]))) can_wrap.send([0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) big_data_size = full_dlc - 6 if (msg.data[0] & 0xF0) == 0x20: # Consecutive if big_data_size > 8: big_data.extend(msg.data[1:]) big_data_size -= 7 else: big_data.extend(msg.data[1:big_data_size + 1]) big_data_size = 0 if big_data_size == 0: for i in range(0, len(big_data), 2): print("DTC: {0}".format(decode_dtc(big_data[i:i + 2]))) with CanActions(arb_id=send_arb_id) as can_wrap: if clear: msg = insert_message_length([0x04], pad=True) can_wrap.send(msg) print("Cleared DTCs and reset MIL") else: print("Fetching Diagnostic Trouble Codes") msg = insert_message_length([0x03], pad=True) can_wrap.send_single_message_with_callback(msg, decode_dtc_pkt) time.sleep(0.5) print("Fetching Pending Diagnostic Trouble Codes") msg = insert_message_length([0x07], pad=True) can_wrap.send_single_message_with_callback(msg, decode_dtc_pkt) time.sleep(1) def dcm_discovery(args): """ Scans for diagnostics support by sending session control against different arbitration IDs. :param: args: A namespace containing min and max """ min_id = args.min max_id = args.max no_stop = args.nostop blacklist = args.blacklist valid_responses = [0x50, 0x7F] def scan_arbitration_ids_to_blacklist(scan_duration): print("Scanning for arbitration IDs to blacklist (-autoblacklist)") ids_to_blacklist = set() def response_handler(msg): """ Blacklists the arbitration ID of a message if it could be misinterpreted as valid diagnostic response :param msg: can.Message instance to check """ if len(msg.data) > 1 and msg.data[1] in valid_responses: ids_to_blacklist.add(msg.arbitration_id) with CanActions() as can_actions: # Listen for matches can_actions.add_listener(response_handler) for i in range(scan_duration, 0, -1): print("\r{0:> 3} seconds left, {1} found".format(i-1, len(ids_to_blacklist)), end="") stdout.flush() time.sleep(1) print("") can_actions.clear_listeners() # Add found matches to blacklist for arb_id in ids_to_blacklist: blacklist.append(arb_id) # Perform automatic blacklist scanning if args.autoblacklist > 0: scan_arbitration_ids_to_blacklist(args.autoblacklist) class Diagnostics: found = False with CanActions() as can_wrap: print("Starting diagnostics service discovery") def response_analyser_wrapper(arb_id): print("\rSending Diagnostic Session Control to 0x{0:04x}".format(arb_id), end="") stdout.flush() def response_analyser(msg): # Ignore blacklisted arbitration IDs if msg.arbitration_id in blacklist: return # Catch both ok and negative response if len(msg.data) >= 2 and msg.data[1] in valid_responses: Diagnostics.found = True print("\nFound diagnostics at arbitration ID 0x{0:04x}, " "reply at 0x{1:04x}".format(arb_id, msg.arbitration_id)) if not no_stop: can_wrap.bruteforce_stop() return response_analyser def discovery_finished(s): if Diagnostics.found: print("\n{0}".format(s)) else: print("\nDiagnostics service could not be found: {0}".format(s)) # Message to bruteforce - [length, session control, default session] message = insert_message_length([0x10, 0x01], pad=True) can_wrap.bruteforce_arbitration_id(message, response_analyser_wrapper, min_id=min_id, max_id=max_id, callback_end=discovery_finished) def service_discovery(args): """ Scans for supported DCM services. Prints a list of all supported services afterwards. :param args: A namespace containing src and dst """ send_arb_id = args.src rcv_arb_id = args.dst with CanActions(arb_id=send_arb_id) as can_wrap: print("Starting DCM service discovery") supported_services = [] def response_analyser_wrapper(service_id): print("\rProbing service 0x{0:02x} ({1} found)".format(service_id, len(supported_services)), end="") stdout.flush() def response_analyser(m): # Skip incoming messages with wrong arbitration ID if m.arbitration_id != rcv_arb_id: return # Skip replies where service is not supported if m.data[3] == 0x11: return # Service supported - add to list supported_services.append(m.data[2]) return response_analyser def done(): print("\nDone!") # Message to bruteforce - [length, service id] msg = insert_message_length([0x00], pad=True) # Index of service id byte in message service_index = 1 try: # Initiate bruteforce can_wrap.bruteforce_data(msg, service_index, response_analyser_wrapper, callback_end=done) finally: # Clear listeners can_wrap.notifier.listeners = [] print("") # Print id and name of all found services for service in supported_services: service_name = DCM_SERVICE_NAMES.get(service, "Unknown service") print("Supported service 0x{0:02x}: {1}".format(service, service_name)) def subfunc_discovery(args): """ Scans for subfunctions of a given service. :param args: A namespace containing src, dst, service, show and i """ send_arb_id = args.src rcv_arb_id = args.dst service_id = args.service show_data = args.show bruteforce_indices = args.i # Sanity checks all_valid = True for i in bruteforce_indices: if not 2 <= i <= 7: print("Invalid bruteforce index '{0}' - must be in range 2-7".format(i)) all_valid = False if not all_valid: return with CanActions(arb_id=send_arb_id) as can_wrap: found_sub_functions = [] print("Starting DCM sub-function discovery") def response_analyser_wrapper(data): print("\rProbing sub-function 0x{0:02x} data {1} (found: {2})".format( service_id, data, len(found_sub_functions)), end="") stdout.flush() def response_analyser(msg): if msg.arbitration_id != rcv_arb_id: return # Response queued - do not handle if msg.data[:4] == [0x03, 0x7f, service_id, 0x78]: can_wrap.current_delay = 1.0 return # Catch ok status elif msg.data[1] - 0x40 == service_id or \ (msg.data[1] == 0x7F and msg.data[3] not in [0x11, 0x12, 0x31, 0x78]): found_sub_functions.append((data, [msg])) elif msg.data[0] == 0x10: # If response takes up multiple frames can_wrap.current_delay = 1.0 found_sub_functions.append((data, [msg])) if show_data: # Cool, give me the rest can_wrap.send([0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) else: # Fine, but I don't want the remaining data can_wrap.send([0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) elif show_data and msg.data[0] & 0xF0 == 0x20: # Parts following a 0x30 in multiple frame response (keep waiting) can_wrap.current_delay = 1.0 found_sub_functions[-1][1].append(msg) else: # We got an answer - no reason to keep waiting can_wrap.current_delay = 0.0 return response_analyser def finished(s): print("\nDone: {0}".format(s)) try: # Message to bruteforce - [length, session control, default session] payload = [service_id] for ind in range(max(bruteforce_indices) - 1): payload.append(0x00) message = insert_message_length(payload, pad=True) can_wrap.bruteforce_data_new(message, bruteforce_indices=bruteforce_indices, callback=response_analyser_wrapper, callback_done=finished) can_wrap.notifier.listeners = [] finally: # Print found functions if len(found_sub_functions) > 0: print("\n\nFound sub-functions for service 0x{0:02x} ({1}):\n".format( service_id, DCM_SERVICE_NAMES.get(service_id, "Unknown service"))) for (sub_function, msgs) in found_sub_functions: print("Sub-function {0}".format(" ".join(sub_function))) if show_data: for message in msgs: print(" {0}".format(message)) else: print("\n\nNo sub-functions were found") def tester_present(args): send_arb_id = args.src delay = args.delay suppress_positive_response = args.spr testerpresent_service_id = 0x3E if suppress_positive_response: sub_function = 0x80 else: sub_function = 0x00 message_data = [0x02, testerpresent_service_id, sub_function, 0x00, 0x00, 0x00, 0x00, 0x00] print("Sending TesterPresent to arbitration ID {0} (0x{0:02x})".format(send_arb_id)) print("\nPress Ctrl+C to stop\n") with CanActions(arb_id=send_arb_id) as can_wrap: counter = 1 while True: can_wrap.send(data=message_data) print("\rCounter:", counter, end="") stdout.flush() time.sleep(delay) counter += 1 def parse_args(args): """ Parser for diagnostics module arguments. :return: Namespace containing action and action-specific arguments :rtype: argparse.Namespace """ parser = argparse.ArgumentParser(prog="cc.py dcm", formatter_class=argparse.RawDescriptionHelpFormatter, description="""Diagnostics module for CaringCaribou""", epilog="""Example usage: cc.py dcm discovery cc.py dcm discovery -blacklist 0x123 0x456 cc.py dcm discovery -autoblacklist 10 cc.py dcm services 0x733 0x633 cc.py dcm subfunc 0x733 0x633 0x22 2 3 cc.py dcm dtc 0x7df 0x7e8 cc.py dcm testerpresent 0x733""") subparsers = parser.add_subparsers(dest="module_function") subparsers.required = True # Parser for diagnostics discovery parser_disc = subparsers.add_parser("discovery") parser_disc.add_argument("-min", type=parse_int_dec_or_hex, default=None) parser_disc.add_argument("-max", type=parse_int_dec_or_hex, default=None) parser_disc.add_argument("-nostop", default=False, action="store_true", help="scan until end of range") parser_disc.add_argument("-blacklist", metavar="B", type=parse_int_dec_or_hex, default=[], nargs="+", help="arbitration IDs to ignore") parser_disc.add_argument("-autoblacklist", metavar="N", type=int, default=0, help="scan for interfering signals for N seconds and blacklist matching arbitration IDs") parser_disc.set_defaults(func=dcm_discovery) # Parser for diagnostics service discovery parser_info = subparsers.add_parser("services") parser_info.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit from") parser_info.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_info.set_defaults(func=service_discovery) # Parser for diagnostics sub-function discovery parser_dump = subparsers.add_parser("subfunc") parser_dump.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit from") parser_dump.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_dump.add_argument("service", type=parse_int_dec_or_hex, help="service ID (e.g. 0x22 for Read DID)") parser_dump.add_argument("-show", action="store_true", help="show data in terminal") parser_dump.add_argument("i", type=int, nargs="+", help="sub-function indices") parser_dump.set_defaults(func=subfunc_discovery) # Parser for DTC parser_dtc = subparsers.add_parser("dtc") parser_dtc.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit from") parser_dtc.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_dtc.add_argument("-clear", action="store_true", help="Clear DTC / MIL") parser_dtc.set_defaults(func=dcm_dtc) # Parser for TesterPresent parser_tp = subparsers.add_parser("testerpresent") parser_tp.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit from") parser_tp.add_argument("-delay", type=float, default=0.5, help="delay between each TesterPresent message") parser_tp.add_argument("-spr", action="store_true", help="suppress positive response") parser_tp.set_defaults(func=tester_present) args = parser.parse_args(args) return args def module_main(arg_list): try: args = parse_args(arg_list) args.func(args) except KeyboardInterrupt: print("\n\nTerminated by user")
19,234
38.016227
120
py
caringcaribou
caringcaribou-master/caringcaribou/modules/send.py
from caringcaribou.utils.can_actions import CanActions from caringcaribou.utils.common import list_to_hex_str, parse_int_dec_or_hex, str_to_int_list from caringcaribou.utils.constants import ARBITRATION_ID_MAX, ARBITRATION_ID_MAX_EXTENDED from time import sleep from sys import exit import argparse import re FILE_LINE_COMMENT_PREFIX = "#" PADDING_BYTE = 0x00 class CanMessage: """ Message wrapper class used by file parsers. """ def __init__(self, arb_id, data, delay, is_extended=None, is_error=False, is_remote=False): """ :param arb_id: int - arbitration ID :param data: list of ints - data bytes :param delay: float - delay in seconds """ self.arb_id = arb_id self.data = data # Negative delays are not allowed self.delay = max([delay, 0.0]) if is_extended is None: self.is_extended = arb_id > ARBITRATION_ID_MAX else: self.is_extended = is_extended self.is_error = is_error self.is_remote = is_remote def parse_messages(msgs, delay, pad): """ Parses a list of message strings. :param delay: Delay between each message :param msgs: list of message strings :param pad: bool indicating whether messages should be padded to 8 bytes :return: list of CanMessage instances """ message_list = [] msg = None try: for msg in msgs: msg_parts = msg.split("#", 1) # Check arbitration ID arb_id = parse_int_dec_or_hex(msg_parts[0]) if arb_id is None: raise ValueError("Invalid arbitration ID: '{0}'".format(msg_parts[0])) if arb_id > ARBITRATION_ID_MAX_EXTENDED: raise ValueError("Arbitration ID too large (max is 0x{0:x})".format(ARBITRATION_ID_MAX_EXTENDED)) # Check data length byte_list = msg_parts[1].split(".") if not 0 < len(byte_list) <= 8: raise ValueError("Invalid data length: {0}".format(len(byte_list))) # Validate data bytes msg_data = [] for byte in byte_list: byte_int = int(byte, 16) if not 0x00 <= byte_int <= 0xff: raise ValueError("Invalid byte value: '{0}'".format(byte)) msg_data.append(byte_int) if pad: # Pad to 8 bytes msg_data.extend([PADDING_BYTE] * (8 - len(msg_data))) fixed_msg = CanMessage(arb_id, msg_data, delay) message_list.append(fixed_msg) # No delay before sending first message return message_list except ValueError as e: print("Invalid message at position {0}: '{1}'\nFailure reason: {2}".format(len(message_list), msg, e)) exit() def parse_candump_line(curr_line, prev_timestamp, force_delay): """ Parses a line on candump log format, e.g. (1499197954.029156) can0 123#c0ffee :param curr_line: str to parse :param prev_timestamp: datetime timestamp of previous message (to calculate delay) :param force_delay: float value to override delay or None to use calculated delay :return: CanMessage representing 'curr_line', datetime.datetime timestamp of 'curr_line' """ segments = curr_line.strip().split(" ") time_stamp = float(segments[0][1:-1]) msg_segs = segments[2].split("#") arb_id = int(msg_segs[0], 16) data = str_to_int_list(msg_segs[1]) if prev_timestamp is None: delay = 0 elif force_delay is not None: delay = force_delay else: delay = time_stamp - prev_timestamp message = CanMessage(arb_id, data, delay) return message, time_stamp def parse_pythoncan_line(curr_line, prev_timestamp, force_delay): """ Parses a line on python-can log format (which differs between versions) :param curr_line: str to parse :param prev_timestamp: datetime timestamp of previous message (to calculate delay) :param force_delay: float value to override delay or None to use calculated delay :return: CanMessage representing 'curr_line', datetime.datetime timestamp of 'curr_line' """ line_regex = re.compile(r"Timestamp: +(?P<timestamp>\d+\.\d+) +ID: (?P<arb_id>[0-9a-fA-F]+) +" r"((\d+)|(?P<is_extended>[SX]) (?P<is_error>[E ]) (?P<is_remote>[R ])) +" r"DLC: +[0-8] +(?P<data>(?:[0-9a-fA-F]{2} ?){0,8}) *(Channel: (?P<channel>\w*))?") parsed_msg = line_regex.match(curr_line) arb_id = int(parsed_msg.group("arb_id"), 16) time_stamp = float(parsed_msg.group("timestamp")) data = list(int(a, 16) for a in parsed_msg.group("data").split(" ") if a) if prev_timestamp is None: delay = 0 elif force_delay is not None: delay = force_delay else: delay = time_stamp - prev_timestamp # Parse flags is_extended = parsed_msg.group("is_extended") == "X" is_error = parsed_msg.group("is_error") == "E" is_remote = parsed_msg.group("is_remote") == "R" message = CanMessage(arb_id, data, delay, is_extended, is_error, is_remote) return message, time_stamp def parse_file(filename, force_delay): """ Parses a file containing CAN traffic logs. :param filename: Path to file :param force_delay: Delay value between each message (if omitted, the delays specified by log file are used) :return: list of CanMessage instances """ try: messages = [] with open(filename, "r") as f: timestamp = None line_parser = None for line in f: # Skip comments and blank lines if line.startswith(FILE_LINE_COMMENT_PREFIX) or len(line.strip()) == 0: continue # First non-comment line - identify log format if line_parser is None: if line.startswith("("): line_parser = parse_candump_line elif line.startswith("Timestamp"): line_parser = parse_pythoncan_line else: raise IOError("Unrecognized file type - could not parse file") # Parse line try: msg, timestamp = line_parser(line, timestamp, force_delay) except (ValueError, AttributeError) as e: raise IOError("Could not parse line:\n '{0}'\n Reason: {1}".format(line.rstrip("\n"), e)) messages.append(msg) return messages except IOError as e: print("ERROR: {0}\n".format(e)) return None def send_messages(messages, loop): """ Sends a list of messages separated by a given delay. :param loop: bool indicating whether the message sequence should be looped (re-sent over and over) :param messages: List of messages, where a message has the format (arb_id, [data_byte]) """ with CanActions(notifier_enabled=False) as can_wrap: loop_counter = 0 while True: for i in range(len(messages)): msg = messages[i] if i != 0 or loop_counter != 0: sleep(msg.delay) print(" Arb_id: 0x{0:08x}, data: {1}".format(msg.arb_id, list_to_hex_str(msg.data, "."))) can_wrap.send(msg.data, msg.arb_id, msg.is_extended, msg.is_error, msg.is_remote) if not loop: break loop_counter += 1 def __handle_parse_messages(args): """ Wrapper for parsing message strings :param args: argument namespace :return: list of CAN messages """ message_strings = args.msg delay = args.delay pad = args.pad messages = parse_messages(message_strings, delay, pad) return messages def __handle_parse_file(args): """ Wrapper for parsing a file containing messages :param args: argument namespace :return: list of CAN messages """ filename = args.filename delay = args.delay messages = parse_file(filename, delay) return messages def parse_args(args): """ Argument parser for the send module. :param args: List of arguments :return: Argument namespace :rtype: argparse.Namespace """ parser = argparse.ArgumentParser(prog="cc.py send", formatter_class=argparse.RawDescriptionHelpFormatter, description="Raw message transmission module for CaringCaribou.\n" "Messages can be passed as command line arguments or through a file.", epilog="""Example usage: cc.py send message 0x7a0#c0.ff.ee.00.11.22.33.44 cc.py send message -d 0.5 123#de.ad.be.ef 124#01.23.45 cc.py send message -p 0x100#11 0x100#22.33 cc.py send file can_dump.txt cc.py send file -d 0.2 can_dump.txt""") subparsers = parser.add_subparsers(dest="module_function") subparsers.required = True # Parser for sending messages from command line cmd_msgs = subparsers.add_parser("message") cmd_msgs.add_argument("msg", nargs="+", help="message on format ARB_ID#DATA where ARB_ID is interpreted " "as hex if it starts with 0x and decimal otherwise. DATA " "consists of 1-8 bytes written in hex and separated by dots.") cmd_msgs.add_argument("--delay", "-d", metavar="D", type=float, default=0, help="delay between messages in seconds") cmd_msgs.add_argument("--loop", "-l", action="store_true", help="loop message sequence (re-send over and over)") cmd_msgs.add_argument("--pad", "-p", action="store_true", help="automatically pad messages to 8 bytes length") cmd_msgs.set_defaults(func=__handle_parse_messages) # Parser for sending messages from file file_msg = subparsers.add_parser("file") file_msg.add_argument("filename", help="path to file") file_msg.add_argument("--delay", "-d", metavar="D", type=float, default=None, help="delay between messages in seconds (overrides timestamps in file)") file_msg.add_argument("--loop", "-l", action="store_true", help="loop message sequence (re-send over and over)") file_msg.set_defaults(func=__handle_parse_file) args = parser.parse_args(args) return args def module_main(args): """ Send module main wrapper. :param args: List of module arguments """ args = parse_args(args) print("Parsing messages") messages = args.func(args) if not messages: print("No messages parsed") else: print(" {0} messages parsed".format(len(messages))) print("Sending messages") send_messages(messages, args.loop)
10,880
37.72242
119
py
caringcaribou
caringcaribou-master/caringcaribou/modules/module_template.py
''' module_template.py This file contains a template for a simple CaringCaribou module. The module's entry point is the 'module_main' function. Steps to add this module to CaringCaribou and run it: 1. Copy this template into the `caringcaribou/modules` directory: $ cp module_template.py my_module.py 2. In `setup.py`, add an entry under `caringcaribou.modules`, referencing your new module like: `my_module = caringcaribou.modules.my_module` 3. Run: `setup.py install` 4. Verify that the module is available, it should be listed in the output of `cc.py -h` 5. Run the following command to run module and show usage instructions: $ cc.py my_module -h ''' from __future__ import print_function import argparse import time from caringcaribou.utils.can_actions import CanActions from caringcaribou.utils.common import list_to_hex_str, parse_int_dec_or_hex def do_stuff(my_arbitration_id): """ Performs some example operations, such as sending and receiving CAN messages. :param my_arbitration_id: The default arbitration id to use when sending messages :type my_arbitration_id: int """ # The notifier should only be enabled when handling incoming traffic using callbacks use_notifier = False # Setup CanActions wrapper to use for receiving and sending messages with CanActions(arb_id=my_arbitration_id, notifier_enabled=use_notifier) as can_wrap: # Define message contents my_message = [0x11, 0x22, 0x33, 0x44] # Send message using the default arbitration ID for can_wrap can_wrap.send(data=my_message) # Send the same message again, but on a custom arbitration ID this time my_custom_arbitration_id = 0x123ABC can_wrap.send(data=my_message, arb_id=my_custom_arbitration_id) # Listen for incoming traffic for a while duration_seconds = 1.0 start_time = time.time() end_time = start_time + duration_seconds while time.time() < end_time: # Check if a message is available msg = can_wrap.bus.recv(0) if msg is None: # No message was available right now - continue listening loop continue # If we reach here, a message was received. Let's print it! print("Received a message on channel", msg.channel) print(" Arb ID: 0x{0:x} ({0})".format(msg.arbitration_id)) data_string = list_to_hex_str(msg.data, ".") print(" Data: ", data_string) # Module logic for message handling goes here if msg.arbitration_id < 0x10: print(" That was a low arbitration ID!") # When we reach here, can_wrap has been closed print("\nDone!") def parse_args(args): """ Argument parser for the template module. :param args: List of arguments :return: Argument namespace :rtype: argparse.Namespace """ parser = argparse.ArgumentParser(prog="cc.py module_template", formatter_class=argparse.RawDescriptionHelpFormatter, description="Descriptive message for the template module", epilog="""Example usage: cc.py module_template cc.py module_template -id 123 cc.py module_template -id 0x1FF""") parser.add_argument("-id", type=parse_int_dec_or_hex, default=0, help="arbitration ID to use") args = parser.parse_args(args) return args def module_main(arg_list): """ Module main wrapper. This is the entry point of the module when called by cc.py :param arg_list: Module argument list passed by cc.py """ try: # Parse arguments args = parse_args(arg_list) # Parse arbitration ID from the arguments arbitration_id = args.id # Time to actually do stuff do_stuff(arbitration_id) except KeyboardInterrupt: print("\n\nTerminated by user")
4,005
34.767857
95
py
caringcaribou
caringcaribou-master/caringcaribou/modules/listener.py
from __future__ import print_function from caringcaribou.utils.can_actions import CanActions from sys import stdout from collections import Counter import argparse def start_listener(falling_sort): """ Counts messages per arbitration ID. Prints a list of IDs afterwards, sorted by number of hits. :param falling_sort: bool indicating whether results should be sorted in falling order """ found_arb_ids = Counter() try: # Listen for messages print("Running listener (press Ctrl+C to exit)") with CanActions(notifier_enabled=False) as can_wrap: for msg in can_wrap.bus: if msg.arbitration_id not in found_arb_ids: print("\rLast ID: 0x{0:08x} ({1} unique arbitration IDs found)".format( msg.arbitration_id, len(found_arb_ids) + 1), end=" ") stdout.flush() found_arb_ids[msg.arbitration_id] += 1 except KeyboardInterrupt: # Print results if len(found_arb_ids) > 0: print("\n\nDetected arbitration IDs:") for (arb_id, hits) in sorted(found_arb_ids.items(), key=lambda x: x[1], reverse=falling_sort): print("Arb id 0x{0:08x} {1} hits".format(arb_id, hits)) else: print("\nNo arbitration IDs were detected.") def parse_args(args): """ Argument parser for the listener module. :param args: List of arguments :return: Argument namespace :rtype: argparse.Namespace """ parser = argparse.ArgumentParser(prog="cc.py listener", formatter_class=argparse.RawDescriptionHelpFormatter, description="Passive listener module for CaringCaribou") parser.add_argument("-r", "--reverse", action="store_true", help="Reversed sorting of results") args = parser.parse_args(args) return args def module_main(args): """ Listener module main wrapper. :param args: List of module arguments """ args = parse_args(args) reverse = args.reverse start_listener(reverse)
2,252
34.203125
98
py
caringcaribou
caringcaribou-master/caringcaribou/modules/fuzzer.py
from __future__ import print_function from sys import version_info, stdout import argparse import random from itertools import product from caringcaribou.utils.can_actions import CanActions from caringcaribou.utils.common import hex_str_to_nibble_list, int_from_byte_list, list_to_hex_str, parse_int_dec_or_hex from caringcaribou.utils.constants import ARBITRATION_ID_MAX, ARBITRATION_ID_MIN, BYTE_MAX, BYTE_MIN from time import sleep # Python 2/3 compatibility if version_info[0] == 2: range = xrange input = raw_input # Number of seconds to wait between messages DELAY_BETWEEN_MESSAGES = 0.01 # Message data length limits MIN_DATA_LENGTH = 1 MAX_DATA_LENGTH = 8 # Max size of random seed if no seed is provided in arguments DEFAULT_SEED_MAX = 2 ** 16 # Number of sub-lists to split message list into per round in 'replay' mode REPLAY_NUMBER_OF_SUB_LISTS = 5 def directive_str(arb_id, data): """ Converts a directive to its string representation :param arb_id: message arbitration ID :param data: message data bytes :return: str representing directive """ data = list_to_hex_str(data, "") directive = "{0:03X}#{1}".format(arb_id, data) return directive def write_directive_to_file_handle(file_handle, arb_id, data): """ Writes a cansend directive to a file :param file_handle: handle for the output file :param arb_id: int arbitration ID :param data: list of data bytes """ directive = directive_str(arb_id, data) file_handle.write("{0}\n".format(directive)) def set_seed(seed=None): """ Seeds the PRNG with 'seed'. If this is None, a seed is pulled from the PRNG instead. :param seed: int to use for seeding """ if seed is None: seed = random.randint(0, DEFAULT_SEED_MAX) print("Seed: {0} (0x{0:x})".format(seed)) random.seed(seed) def parse_directive(directive): """ Parses a cansend directive :param directive: str representing a cansend directive :return: tuple (int arbitration_id, [int data_byte]) """ segments = directive.split("#") arb_id = int(segments[0], 16) data_str = segments[1] data = [int(data_str[i:i + 2], 16) for i in range(0, len(data_str), 2)] return arb_id, data def apply_fuzzed_data(initial_data, fuzzed_nibbles, bitmap): """ Applies 'fuzzed_nibbles' on top of 'initial_data', for all indices where 'bitmap' is True. Returns result as a list of bytes. Example: apply_fuzzed_data([0x2, 0x4, 0xA, 0xB], [0x5, 0xF], [False, True, True, False]) gives the following result: [0x25, 0xFB] :param initial_data: list of initial data nibbles :param fuzzed_nibbles: list of nibbles to apply :param bitmap: list of bool values, indicating where to apply fuzzed nibbles :return: list of bytes """ fuzz_index = 0 result_bytes = [] for index in range(0, len(bitmap), 2): # Apply fuzzed nibbles on top of initial data if bitmap[index]: high_nibble = fuzzed_nibbles[fuzz_index] fuzz_index += 1 else: high_nibble = initial_data[index] if bitmap[index + 1]: low_nibble = fuzzed_nibbles[fuzz_index] fuzz_index += 1 else: low_nibble = initial_data[index + 1] current_byte = (high_nibble << 4) + low_nibble result_bytes.append(current_byte) return result_bytes def nibbles_to_bytes(nibbles): """ Converts a list of nibbles into a list of corresponding bytes. Example: nibbles_to_bytes([0x2, 0x1, 0xF, 0xA, 0x3, 0xC]) gives [0x21, 0xFA, 0x3C] :param nibbles: list of nibble values :return: list of int values (bytes) """ result_bytes = [] for index in range(0, len(nibbles), 2): high_nibble = nibbles[index] low_nibble = nibbles[index + 1] current_byte = (high_nibble << 4) + low_nibble result_bytes.append(current_byte) return result_bytes def split_lists(full_list, pieces): """ Generator function which splits 'full_list' into smaller sub-lists :param full_list: list to split :param pieces: number of sub-lists to produce :return: yields one sub-list at a time """ length = len(full_list) for i in range(pieces): sub_list = full_list[i * length // pieces: (i + 1) * length // pieces] if len(sub_list) == 0: # Skip empty sub-lists (e.g. if a list of 2 elements is split into 3 parts, one will be empty) continue yield sub_list def get_random_arbitration_id(min_id, max_id): """ Returns a random arbitration ID in the range min_id <= arb_id <= max_id :param min_id: int minimum allowed arbitration ID (inclusive) :param max_id: int maximum allowed arbitration ID (inclusive) :return: int arbitration ID """ arb_id = random.randint(min_id, max_id) return arb_id def get_random_data(min_length, max_length): """ Generates a list of random data bytes, whose length lies in the interval 'min_length' to 'max_length' :param min_length: int minimum length :param max_length: int maximum length :return: list of randomized bytes """ # Decide number of bytes to generate data_length = random.randint(min_length, max_length) # Generate random bytes data = [] for i in range(data_length): data_byte = random.randint(BYTE_MIN, BYTE_MAX) data.append(data_byte) return data def parse_directives_from_file(filename): """ Parses 'filename' and returns a list of all directives contained within :param filename: str file to parse :return: list of str directives """ print("Parsing messages from {0}".format(filename)) line_number = 0 with open(filename, "r") as fd: directives = [] for directive in fd: line_number += 1 directive = directive.rstrip() if directive: try: composite = parse_directive(directive) directives.append(composite) except ValueError: print(" Error: Could not parse message on line {0}: {1}".format(line_number, directive)) print(" {0} messages parsed".format(len(directives))) return directives def pad_to_even_length(original_list, padding=0x0): """ Prepends 'padding' to 'original_list' if its length is uneven. Examples: pad_to_even_length([1, 2, 3]) gives [0, 1, 2, 3] pad_to_even_length([1, 2]) gives [1, 2] :param original_list: list of elements :param padding: element to prepend :return: list of even length """ if len(original_list) % 2 == 1: original_list.insert(0, padding) return original_list def random_fuzz(static_arb_id=None, static_data=None, filename=None, min_id=ARBITRATION_ID_MIN, max_id=ARBITRATION_ID_MAX, min_data_length=MIN_DATA_LENGTH, max_data_length=MAX_DATA_LENGTH, start_index=0, show_status=True, seed=None): """ A simple random fuzzer algorithm, which sends random or static data to random or static arbitration IDs :param static_arb_id: int representing static arbitration ID :param static_data: list of bytes representing static data :param filename: file to write cansend directives to :param min_id: minimum allowed arbitration ID :param max_id: maximum allowed arbitration ID :param min_data_length: minimum allowed data length :param max_data_length: maximum allowed data length :param start_index: int index to start at (can be used to resume interrupted session) :param show_status: bool indicating whether current message and counter should be printed to stdout :param seed: use given seed instead of random seed """ # Sanity checks if static_arb_id is not None and static_data is not None: raise ValueError("Both static arbitration ID and static data cannot be set at the same time") if not 0 <= min_id < max_id <= ARBITRATION_ID_MAX: raise ValueError("Invalid value for min_id and/or max_id") if not MIN_DATA_LENGTH <= min_data_length <= max_data_length <= MAX_DATA_LENGTH: raise ValueError("Invalid value for min_data_length ({0}) and/or max_data_length ({1})".format( min_data_length, max_data_length)) if static_data is not None and len(static_data) > MAX_DATA_LENGTH: raise ValueError("static_data ({0} bytes) must not be more than {1} bytes long".format( len(static_data), MAX_DATA_LENGTH)) if not 0 <= start_index: raise ValueError("Invalid start index '{0}', must be 0 or larger".format(start_index)) # Seed handling set_seed(seed) # Define a callback function which will handle incoming messages def response_handler(msg): if msg.arbitration_id != arb_id or list(msg.data) != data: directive = directive_str(arb_id, data) print("\rDirective: {0} (index {1})".format(directive, current_index)) print(" Received message: {0}".format(msg)) arb_id = None data = None file_logging_enabled = filename is not None output_file = None try: if file_logging_enabled: output_file = open(filename, "a") with CanActions() as can_wrap: # Register callback handler for incoming messages current_index = 0 messages_sent = 0 can_wrap.add_listener(response_handler) if show_status: print("Starting at index {0}\n".format(start_index)) # Fuzzing logic while True: # Set arbitration ID if static_arb_id is None: # Use a random arbitration ID arb_id = get_random_arbitration_id(min_id, max_id) else: # Use the static arbitration ID arb_id = static_arb_id # Set data if static_data is None: data = get_random_data(min_data_length, max_data_length) else: data = static_data # If start index is not reached yet, continue without sending and sleeping if current_index < start_index: current_index += 1 continue if show_status: print("\rMessages sent: {0}, index: {1}".format(messages_sent, current_index), end="") stdout.flush() # Send message can_wrap.send(data=data, arb_id=arb_id) messages_sent += 1 # Log to file if file_logging_enabled: write_directive_to_file_handle(output_file, arb_id, data) sleep(DELAY_BETWEEN_MESSAGES) current_index += 1 except IOError as e: print("ERROR: {0}".format(e)) finally: if output_file is not None: output_file.close() def bruteforce_fuzz(arb_id, initial_data, data_bitmap, filename=None, start_index=0, show_progress=True, show_responses=True): """ Performs a brute force of selected data nibbles for a given arbitration ID. Nibble selection is controlled by bool list 'data_bitmap'. Example: bruteforce_fuzz(0x123, [0x1, 0x2, 0xA, 0xB], [True, False, False, True]) will cause the following messages to be sent: 0x123#02A0 0x123#02A1 0x123#02A2 (...) 0x123#02AF 0x123#12A0 0x123#12A1 (...) 0x123#F2AF :param arb_id: int arbitration ID :param initial_data: list of nibbles (ints in interval 0x0-0xF, inclusive) :param data_bitmap: list of bool values, representing which nibbles of 'initial_data' to bruteforce :param filename: file to write cansend directives to :param start_index: int index to start at (can be used to resume interrupted session) :param show_progress: bool indicating whether progress should be printed to stdout :param show_responses: bool indicating whether responses should be printed to stdout """ # Sanity checks if not 2 <= len(initial_data) <= 16: raise ValueError("Invalid initial data: must be between 2 and 16 nibbles") if not len(initial_data) % 2 == 0: raise ValueError("Invalid initial data: must have an even length") if not len(initial_data) == len(data_bitmap): raise ValueError("Initial data ({0}) and data bitmap ({1}) must have the same length".format( len(initial_data), len(data_bitmap))) number_of_nibbles_to_bruteforce = sum(data_bitmap) end_index = 16 ** number_of_nibbles_to_bruteforce if not 0 <= start_index <= end_index: raise ValueError("Invalid start index '{0}', current range is [0-{1}]".format(start_index, end_index)) def response_handler(msg): # Callback handler for printing incoming messages if msg.arbitration_id != arb_id or list(msg.data) != output_data: response_directive = directive_str(msg.arbitration_id, msg.data) print(" Received {0}".format(response_directive)) # Initialize fuzzed nibble generator nibble_values = range(0xF + 1) fuzz_data = product(nibble_values, repeat=number_of_nibbles_to_bruteforce) file_logging_enabled = filename is not None output_file = None output_data = [] try: if file_logging_enabled: output_file = open(filename, "a") with CanActions(arb_id=arb_id) as can_wrap: if show_progress: print("Starting at index {0} of {1}\n".format(start_index, end_index)) if show_responses: can_wrap.add_listener(response_handler) message_count = 0 # Traverse all outputs from fuzz generator for current_fuzzed_nibbles in fuzz_data: # Skip handling until start_index is met if message_count < start_index: message_count += 1 continue # Apply fuzzed data output_data = apply_fuzzed_data(initial_data, current_fuzzed_nibbles, data_bitmap) # Send message can_wrap.send(output_data) message_count += 1 if show_progress: print("\rCurrent: {0} Index: {1}".format(list_to_hex_str(output_data, " "), message_count), end="") stdout.flush() # Log to file if file_logging_enabled: write_directive_to_file_handle(output_file, arb_id, output_data) sleep(DELAY_BETWEEN_MESSAGES) if show_progress: print() finally: if output_file is not None: output_file.close() if show_progress: print("Brute force finished") def mutate_fuzz(initial_arb_id, initial_data, arb_id_bitmap, data_bitmap, filename=None, start_index=0, show_status=True, show_responses=False, seed=None): """ Performs mutation based fuzzing of selected nibbles of a given arbitration ID and data. Nibble selection is controlled by bool lists 'arb_id_bitmap' and 'data_bitmap'. :param initial_arb_id: list of nibbles (ints in interval 0x0-0xF, inclusive) :param initial_data: list of nibbles (ints in interval 0x0-0xF, inclusive) :param arb_id_bitmap: list of bool values, representing which nibbles of 'initial_arb_id' to bruteforce :param data_bitmap: list of bool values, representing which nibbles of 'initial_data' to bruteforce :param filename: file to write cansend directives to :param start_index: int index to start at (can be used to resume interrupted session) :param show_status: bool indicating whether current message and counter should be printed to stdout :param show_responses: bool indicating whether responses should be printed to stdout :param seed: use given seed instead of random seed """ # Sanity checks if not 0 <= start_index: raise ValueError("Invalid start index '{0}', must be 0 or larger".format(start_index)) # Seed handling set_seed(seed) def response_handler(msg): # Callback handler for printing incoming messages if msg.arbitration_id != arb_id or list(msg.data) != data: response_directive = directive_str(msg.arbitration_id, msg.data) print(" Received {0}".format(response_directive)) number_of_nibbles_to_fuzz_arb_id = sum(arb_id_bitmap) number_of_nibbles_to_fuzz_data = sum(data_bitmap) file_logging_enabled = filename is not None output_file = None # Set initial values - needed in case they are static data = None arb_id = None if number_of_nibbles_to_fuzz_data == 0: data = apply_fuzzed_data(initial_data, [], data_bitmap) if number_of_nibbles_to_fuzz_arb_id == 0: arb_id = int_from_byte_list(apply_fuzzed_data(initial_arb_id, [], arb_id_bitmap)) try: if file_logging_enabled: output_file = open(filename, "a") with CanActions() as can_wrap: current_index = 0 messages_sent = 0 if show_responses: can_wrap.add_listener(response_handler) while True: if number_of_nibbles_to_fuzz_arb_id > 0: # Mutate arbitration ID fuzzed_nibbles_arb_id = [random.randint(0, 0xF) for _ in range(number_of_nibbles_to_fuzz_arb_id)] arb_id_bytes = apply_fuzzed_data(initial_arb_id, fuzzed_nibbles_arb_id, arb_id_bitmap) arb_id = int_from_byte_list(arb_id_bytes) if number_of_nibbles_to_fuzz_data > 0: # Mutate data fuzzed_nibbles_data = [random.randint(0, 0xF) for _ in range(number_of_nibbles_to_fuzz_data)] data = apply_fuzzed_data(initial_data, fuzzed_nibbles_data, data_bitmap) if current_index < start_index: current_index += 1 continue if show_status: print("\rSending {0:04x} # {1} ({2} sent, index {3})".format( arb_id, list_to_hex_str(data, " "), messages_sent, current_index), end="") stdout.flush() can_wrap.send(data, arb_id) messages_sent += 1 # Log to file if file_logging_enabled: write_directive_to_file_handle(output_file, arb_id, data) sleep(DELAY_BETWEEN_MESSAGES) current_index += 1 finally: if output_file is not None: output_file.close() def replay_fuzz(directives, show_requests, show_responses): """ Replay cansend directives from 'filename' :param directives: list of (int arb_id, list data) tuples :param show_requests: bool indicating whether requests should be printed to stdout :param show_responses: bool indicating whether responses should be printed to stdout """ # Define a callback function which will handle incoming messages def response_handler(msg): if msg.arbitration_id != arb_id or list(msg.data) != data: if not show_requests: # Print last sent request print("Sent: {0}".format(directive)) print(" Received: {0}".format(directive_str(msg.arbitration_id, msg.data))) arb_id = None data = None count = 0 with CanActions() as can_wrap: if show_responses: # Enable callback handler for incoming messages can_wrap.add_listener(response_handler) for arb_id, data in directives: count += 1 directive = directive_str(arb_id, data) can_wrap.send(data=data, arb_id=arb_id) if show_requests: print("Sending ({0}) {1}".format(count, directive)) sleep(DELAY_BETWEEN_MESSAGES) print("Replay finished") def identify_fuzz(all_composites, show_responses): """ Replays a list of composites causing an effect, prompting for input to help isolate the message causing the effect :param all_composites: list of composites :param show_responses: bool indicating whether responses should be printed to stdout :return: str directive if message is found, None otherwise """ def response_handler(msg): if msg.arbitration_id != arb_id or list(msg.data) != data: response_directive = directive_str(msg.arbitration_id, msg.data) print(" Received {0}".format(response_directive)) arb_id = None data = None composites = None directive = None repeat = False with CanActions() as can_wrap: try: # Send all messages in first round gen = split_lists(all_composites, 1) while True: print() if repeat: # Keep previous list of messages to send repeat = False else: # Get next list of messages to send composites = next(gen) if show_responses: # Enable callback handler for incoming messages can_wrap.add_listener(response_handler) # Send messages for index in range(len(composites)): composite = composites[index] arb_id = composite[0] data = composite[1] directive = directive_str(arb_id, data) can_wrap.send(data=data, arb_id=arb_id) print("Sending ({0}/{1}) {2}".format(index+1, len(composites), directive)) sleep(DELAY_BETWEEN_MESSAGES) # Disable callback handler for incoming messages can_wrap.clear_listeners() # Get user input print("\nWas the desired effect observed?") valid_response = False while not valid_response: valid_response = True response = input("(y)es | (n)o | (r)eplay | (q)uit: ").lower() if response == "y": if len(composites) == 1: # Single message found print("\nMatch found! Message causing effect: {0}".format(directive)) return directive else: # Split into even smaller lists of messages gen = split_lists(composites, REPLAY_NUMBER_OF_SUB_LISTS) elif response == "n": # Try next list of messages pass elif response == "r": # Repeat batch repeat = True elif response == "q": # Quit return None else: # Invalid choice - ask again print("Invalid choice") valid_response = False except StopIteration: # No more messages to try - give up print("\nNo match was found.") return None def __handle_random(args): data = None if args.data is not None: data_nibbles = hex_str_to_nibble_list(args.data) padded_nibbles = pad_to_even_length(data_nibbles) data = nibbles_to_bytes(padded_nibbles) random_fuzz(static_arb_id=args.id, static_data=data, filename=args.file, min_data_length=args.min, max_data_length=args.max, start_index=args.index, seed=args.seed) def parse_hex_and_dot_indices(values, dot_index_marker="."): """ Parses a str consisting of hex nibble values and 'dot_index_marker' and returns a tuple consisting of a list of (int or None) values and a boolean list of dot indices. Example: parse_hex_and_dot_indices("1.34AB..") gives ([1, None, 3, 4, 0xA, 0xB, None, None], [False, True, False, False, False, False, True, True]) :param values: str input consisting of hex and 'dot_index_marker' values :param dot_index_marker: str character which identifies dot indices :return: tuple with list of int/None values and list of int dot indices """ dot_indices = [] hex_data = [] # Pad to even length if needed if len(values) % 2 == 1: hex_data.append(0) dot_indices.append(False) # Parse values for i in range(len(values)): nibble = values[i] is_dot_index = nibble == dot_index_marker dot_indices.append(is_dot_index) if is_dot_index: hex_nibble = None else: hex_nibble = int(nibble, 16) hex_data.append(hex_nibble) return hex_data, dot_indices def __handle_bruteforce(args): data, data_bitmap = parse_hex_and_dot_indices(args.data) bruteforce_fuzz(arb_id=args.arb_id, initial_data=data, data_bitmap=data_bitmap, filename=args.file, start_index=args.index, show_progress=True, show_responses=args.responses) def __handle_mutate(args): arb_id, id_bitmap = parse_hex_and_dot_indices(args.arb_id) data, data_bitmap = parse_hex_and_dot_indices(args.data) mutate_fuzz(initial_arb_id=arb_id, initial_data=data, arb_id_bitmap=id_bitmap, data_bitmap=data_bitmap, filename=args.file, start_index=args.index, show_responses=args.responses, seed=args.seed) def __handle_replay(args): filename = args.filename try: directives = parse_directives_from_file(filename) print("Sending messages") replay_fuzz(directives=directives, show_requests=args.requests, show_responses=args.responses) except IOError as e: print("ERROR: {0}".format(e)) def __handle_identify(args): try: directives = parse_directives_from_file(args.filename) # Call handling function identify_fuzz(directives, show_responses=args.responses) except IOError as e: print("IOError:", e) def parse_args(args): """ Argument parser for the fuzzer module. :param args: List of arguments :return: Argument namespace :rtype: argparse.Namespace """ global DELAY_BETWEEN_MESSAGES parser = argparse.ArgumentParser(prog="cc.py fuzzer", formatter_class=argparse.RawDescriptionHelpFormatter, description="Fuzzing module for CaringCaribou", epilog="""Example usage: ./cc.py fuzzer random ./cc.py fuzzer random -min 4 -seed 0xabc123 -f log.txt ./cc.py fuzzer brute 0x123 12ab..78 ./cc.py fuzzer mutate 7f.. 12ab.... ./cc.py fuzzer replay log.txt ./cc.py fuzzer identify log.txt""") subparsers = parser.add_subparsers(dest="module_function") subparsers.required = True # Random fuzzer cmd_random = subparsers.add_parser("random", help="Random fuzzer for messages and arbitration IDs") cmd_random.add_argument("-id", type=parse_int_dec_or_hex, default=None, help="set static arbitration ID") cmd_random.add_argument("-data", "-d", default=None, help="set static data") cmd_random.add_argument("-file", "-f", default=None, help="log file for cansend directives") cmd_random.add_argument("-min", type=int, default=MIN_DATA_LENGTH, help="minimum data length") cmd_random.add_argument("-max", type=int, default=MAX_DATA_LENGTH, help="maximum data length") cmd_random.add_argument("-index", "-i", metavar="I", type=parse_int_dec_or_hex, default=0, help="start index (for resuming previous session)") cmd_random.add_argument("-seed", "-s", metavar="S", type=parse_int_dec_or_hex, default=None, help="set random seed") cmd_random.add_argument("-delay", type=float, metavar="D", default=DELAY_BETWEEN_MESSAGES, help="delay between messages") cmd_random.set_defaults(func=__handle_random) # Brute force fuzzer cmd_brute = subparsers.add_parser("brute", help="Brute force selected nibbles in a message") cmd_brute.add_argument("arb_id", type=parse_int_dec_or_hex, help="arbitration ID") cmd_brute.add_argument("data", help="hex data where dots mark indices to bruteforce, e.g. 123.AB..") cmd_brute.add_argument("-file", "-f", default=None, help="log file for cansend directives") cmd_brute.add_argument("-responses", "-r", action="store_true", help="print responses to stdout") cmd_brute.add_argument("-index", "-i", metavar="I", type=parse_int_dec_or_hex, default=0, help="start index (for resuming previous session)") cmd_brute.add_argument("-delay", type=float, metavar="D", default=DELAY_BETWEEN_MESSAGES, help="delay between messages") cmd_brute.set_defaults(func=__handle_bruteforce) # Mutate fuzzer cmd_mutate = subparsers.add_parser("mutate", help="Mutate selected nibbles in arbitration ID and message") cmd_mutate.add_argument("arb_id", help="hex arbitration ID where dots mark indices to mutate, e.g. 7f..") cmd_mutate.add_argument("data", help="hex data where dots mark indices to mutate, e.g. 123.AB..") cmd_mutate.add_argument("-responses", "-r", action="store_true", help="print responses to stdout") cmd_mutate.add_argument("-file", "-f", default=None, help="log file for cansend directives") cmd_mutate.add_argument("-seed", "-s", metavar="S", type=parse_int_dec_or_hex, default=None, help="set random seed") cmd_mutate.add_argument("-index", "-i", metavar="I", type=parse_int_dec_or_hex, default=0, help="start index (for resuming previous session)") cmd_mutate.add_argument("-delay", type=float, metavar="D", default=DELAY_BETWEEN_MESSAGES, help="delay between messages") cmd_mutate.set_defaults(func=__handle_mutate) # Replay cmd_replay = subparsers.add_parser("replay", help="Replay a previously recorded directive file") cmd_replay.add_argument("filename", help="input directive file to replay") cmd_replay.add_argument("-requests", "-req", action="store_true", help="print requests to stdout") cmd_replay.add_argument("-responses", "-res", action="store_true", help="print responses to stdout") cmd_replay.add_argument("-delay", type=float, metavar="D", default=DELAY_BETWEEN_MESSAGES, help="delay between messages") cmd_replay.set_defaults(func=__handle_replay) # Identify (replay with response mapping) cmd_identify = subparsers.add_parser("identify", help="Replay and identify message causing a specific event") cmd_identify.add_argument("filename", help="input directive file to replay") cmd_identify.add_argument("-responses", "-res", action="store_true", help="print responses to stdout") cmd_identify.add_argument("-delay", type=float, metavar="D", default=DELAY_BETWEEN_MESSAGES, help="delay between messages") cmd_identify.set_defaults(func=__handle_identify) args = parser.parse_args(args) if "delay" in args: DELAY_BETWEEN_MESSAGES = args.delay return args def module_main(arg_list): """ Fuzz module main wrapper. :param arg_list: Module argument list passed by cc.py """ try: # Parse arguments args = parse_args(arg_list) # Call appropriate function args.func(args) except KeyboardInterrupt: print("\n\nTerminated by user")
31,850
39.064151
120
py
caringcaribou
caringcaribou-master/caringcaribou/modules/uds.py
from __future__ import print_function from caringcaribou.utils.can_actions import auto_blacklist from caringcaribou.utils.common import list_to_hex_str, parse_int_dec_or_hex from caringcaribou.utils.constants import ARBITRATION_ID_MAX, ARBITRATION_ID_MAX_EXTENDED from caringcaribou.utils.constants import ARBITRATION_ID_MIN from caringcaribou.utils.iso15765_2 import IsoTp from caringcaribou.utils.iso14229_1 import Constants, Iso14229_1, NegativeResponseCodes, Services, ServiceID from sys import stdout, version_info import argparse import datetime import time # Handle large ranges efficiently in both python 2 and 3 if version_info[0] == 2: range = xrange UDS_SERVICE_NAMES = { 0x10: "DIAGNOSTIC_SESSION_CONTROL", 0x11: "ECU_RESET", 0x14: "CLEAR_DIAGNOSTIC_INFORMATION", 0x19: "READ_DTC_INFORMATION", 0x20: "RETURN_TO_NORMAL", 0x22: "READ_DATA_BY_IDENTIFIER", 0x23: "READ_MEMORY_BY_ADDRESS", 0x24: "READ_SCALING_DATA_BY_IDENTIFIER", 0x27: "SECURITY_ACCESS", 0x28: "COMMUNICATION_CONTROL", 0x2A: "READ_DATA_BY_PERIODIC_IDENTIFIER", 0x2C: "DYNAMICALLY_DEFINE_DATA_IDENTIFIER", 0x2D: "DEFINE_PID_BY_MEMORY_ADDRESS", 0x2E: "WRITE_DATA_BY_IDENTIFIER", 0x2F: "INPUT_OUTPUT_CONTROL_BY_IDENTIFIER", 0x31: "ROUTINE_CONTROL", 0x34: "REQUEST_DOWNLOAD", 0x35: "REQUEST_UPLOAD", 0x36: "TRANSFER_DATA", 0x37: "REQUEST_TRANSFER_EXIT", 0x38: "REQUEST_FILE_TRANSFER", 0x3D: "WRITE_MEMORY_BY_ADDRESS", 0x3E: "TESTER_PRESENT", 0x7F: "NEGATIVE_RESPONSE", 0x83: "ACCESS_TIMING_PARAMETER", 0x84: "SECURED_DATA_TRANSMISSION", 0x85: "CONTROL_DTC_SETTING", 0x86: "RESPONSE_ON_EVENT", 0x87: "LINK_CONTROL" } NRC_NAMES = { 0x00: "POSITIVE_RESPONSE", 0x10: "GENERAL_REJECT", 0x11: "SERVICE_NOT_SUPPORTED", 0x12: "SUB_FUNCTION_NOT_SUPPORTED", 0x13: "INCORRECT_MESSAGE_LENGTH_OR_INVALID_FORMAT", 0x14: "RESPONSE_TOO_LONG", 0x21: "BUSY_REPEAT_REQUEST", 0x22: "CONDITIONS_NOT_CORRECT", 0x24: "REQUEST_SEQUENCE_ERROR", 0x25: "NO_RESPONSE_FROM_SUBNET_COMPONENT", 0x26: "FAILURE_PREVENTS_EXECUTION_OF_REQUESTED_ACTION", 0x31: "REQUEST_OUT_OF_RANGE", 0x33: "SECURITY_ACCESS_DENIED", 0x35: "INVALID_KEY", 0x36: "EXCEEDED_NUMBER_OF_ATTEMPTS", 0x37: "REQUIRED_TIME_DELAY_NOT_EXPIRED", 0x70: "UPLOAD_DOWNLOAD_NOT_ACCEPTED", 0x71: "TRANSFER_DATA_SUSPENDED", 0x72: "GENERAL_PROGRAMMING_FAILURE", 0x73: "WRONG_BLOCK_SEQUENCE_COUNTER", 0x78: "REQUEST_CORRECTLY_RECEIVED_RESPONSE_PENDING", 0x7E: "SUB_FUNCTION_NOT_SUPPORTED_IN_ACTIVE_SESSION", 0x7F: "SERVICE_NOT_SUPPORTED_IN_ACTIVE_SESSION", 0x81: "RPM_TOO_HIGH", 0x82: "RPM_TOO_LOW", 0x83: "ENGINE_IS_RUNNING", 0x84: "ENGINE_IS_NOT_RUNNING", 0x85: "ENGINE_RUN_TIME_TOO_LOW", 0x86: "TEMPERATURE_TOO_HIGH", 0x87: "TEMPERATURE_TOO_LOW", 0x88: "VEHICLE_SPEED_TOO_HIGH", 0x89: "VEHICLE_SPEED_TOO_LOW", 0x8A: "THROTTLE_PEDAL_TOO_HIGH", 0x8B: "THROTTLE_PEDAL_TOO_LOW", 0x8C: "TRANSMISSION_RANGE_NOT_IN_NEUTRAL", 0x8D: "TRANSMISSION_RANGE_NOT_IN_GEAR", 0x8F: "BRAKE_SWITCHES_NOT_CLOSED", 0x90: "SHIFT_LEVER_NOT_IN_PARK", 0x91: "TORQUE_CONVERTER_CLUTCH_LOCKED", 0x92: "VOLTAGE_TOO_HIGH", 0x93: "VOLTAGE_TOO_LOW" } DELAY_DISCOVERY = 0.01 DELAY_TESTER_PRESENT = 0.5 DELAY_SECSEED_RESET = 0.01 TIMEOUT_SERVICES = 0.2 TIMEOUT_SUBSERVICES = 0.02 # Max number of arbitration IDs to backtrack during verification VERIFICATION_BACKTRACK = 5 # Extra time in seconds to wait for responses during verification VERIFICATION_EXTRA_DELAY = 0.5 BYTE_MIN = 0x00 BYTE_MAX = 0xFF DUMP_DID_MIN = 0x0000 DUMP_DID_MAX = 0xFFFF DUMP_DID_TIMEOUT = 0.2 def uds_discovery(min_id, max_id, blacklist_args, auto_blacklist_duration, delay, verify, print_results=True): """Scans for diagnostics support by brute forcing session control messages to different arbitration IDs. Returns a list of all (client_arb_id, server_arb_id) pairs found. :param min_id: start arbitration ID value :param max_id: end arbitration ID value :param blacklist_args: blacklist for arbitration ID values :param auto_blacklist_duration: seconds to scan for interfering arbitration IDs to blacklist automatically :param delay: delay between each message :param verify: whether found arbitration IDs should be verified :param print_results: whether results should be printed to stdout :type min_id: int :type max_id: int :type blacklist_args: [int] :type auto_blacklist_duration: float :type delay: float :type verify: bool :type print_results: bool :return: list of (client_arbitration_id, server_arbitration_id) pairs :rtype [(int, int)] """ # Set defaults if min_id is None: min_id = ARBITRATION_ID_MIN if max_id is None: if min_id <= ARBITRATION_ID_MAX: max_id = ARBITRATION_ID_MAX else: # If min_id is extended, use an extended default max_id as well max_id = ARBITRATION_ID_MAX_EXTENDED if auto_blacklist_duration is None: auto_blacklist_duration = 0 if blacklist_args is None: blacklist_args = [] # Sanity checks if max_id < min_id: raise ValueError("max_id must not be smaller than min_id -" " got min:0x{0:x}, max:0x{1:x}".format(min_id, max_id)) if auto_blacklist_duration < 0: raise ValueError("auto_blacklist_duration must not be smaller " "than 0, got {0}'".format(auto_blacklist_duration)) diagnostic_session_control = Services.DiagnosticSessionControl service_id = diagnostic_session_control.service_id sub_function = diagnostic_session_control.DiagnosticSessionType.DEFAULT_SESSION session_control_data = [service_id, sub_function] valid_session_control_responses = [0x50, 0x7F] def is_valid_response(message): return (len(message.data) >= 2 and message.data[1] in valid_session_control_responses) found_arbitration_ids = [] with IsoTp(None, None) as tp: blacklist = set(blacklist_args) # Perform automatic blacklist scan if auto_blacklist_duration > 0: auto_bl_arb_ids = auto_blacklist(tp.bus, auto_blacklist_duration, is_valid_response, print_results) blacklist |= auto_bl_arb_ids # Prepare session control frame sess_ctrl_frm = tp.get_frames_from_message(session_control_data) send_arb_id = min_id - 1 while send_arb_id < max_id: send_arb_id += 1 if print_results: print("\rSending Diagnostic Session Control to 0x{0:04x}" .format(send_arb_id), end="") stdout.flush() # Send Diagnostic Session Control tp.transmit(sess_ctrl_frm, send_arb_id, None) end_time = time.time() + delay # Listen for response while time.time() < end_time: msg = tp.bus.recv(0) if msg is None: # No response received continue if msg.arbitration_id in blacklist: # Ignore blacklisted arbitration IDs continue if is_valid_response(msg): # Valid response if verify: # Verification - backtrack the latest IDs and # verify that the same response is received verified = False # Set filter to only receive messages for the # arbitration ID being verified tp.set_filter_single_arbitration_id(msg.arbitration_id) if print_results: print("\n Verifying potential response from " "0x{0:04x}".format(send_arb_id)) verify_id_range = range(send_arb_id, send_arb_id - VERIFICATION_BACKTRACK, -1) for verify_arb_id in verify_id_range: if print_results: print(" Resending 0x{0:0x}... " .format(verify_arb_id), end=" ") tp.transmit(sess_ctrl_frm, verify_arb_id, None) # Give some extra time for verification, in # case of slow responses verification_end_time = (time.time() + delay + VERIFICATION_EXTRA_DELAY) while time.time() < verification_end_time: verification_msg = tp.bus.recv(0) if verification_msg is None: continue if is_valid_response(verification_msg): # Verified verified = True # Update send ID - if server responds # slowly, initial value may be faulty. # Also ensures we resume searching on # the next arb ID after the actual # match, rather than the one after the # last potential match (which could lead # to false negatives if multiple servers # listen to adjacent arbitration IDs and # respond slowly) send_arb_id = verify_arb_id break if print_results: # Print result if verified: print("Success") else: print("No response") if verified: # Verification succeeded - stop checking break # Remove filter after verification tp.clear_filters() if not verified: # Verification failed - move on if print_results: print(" False match - skipping") continue if print_results: if not verify: # Blank line needed print() print("Found diagnostics server " "listening at 0x{0:04x}, " "response at 0x{1:04x}" .format(send_arb_id, msg.arbitration_id)) # Add found arbitration ID pair found_arb_id_pair = (send_arb_id, msg.arbitration_id) found_arbitration_ids.append(found_arb_id_pair) if print_results: print() return found_arbitration_ids def __uds_discovery_wrapper(args): """Wrapper used to initiate a UDS discovery scan""" min_id = args.min max_id = args.max blacklist = args.blacklist auto_blacklist_duration = args.autoblacklist delay = args.delay verify = not args.skipverify print_results = True try: arb_id_pairs = uds_discovery(min_id, max_id, blacklist, auto_blacklist_duration, delay, verify, print_results) if len(arb_id_pairs) == 0: # No UDS discovered print("\nDiagnostics service could not be found.") else: # Print result table print("\nIdentified diagnostics:\n") table_line = "+------------+------------+" print(table_line) print("| CLIENT ID | SERVER ID |") print(table_line) for (client_id, server_id) in arb_id_pairs: print("| 0x{0:08x} | 0x{1:08x} |" .format(client_id, server_id)) print(table_line) except ValueError as e: print("Discovery failed: {0}".format(e)) def service_discovery(arb_id_request, arb_id_response, timeout, min_id=BYTE_MIN, max_id=BYTE_MAX, print_results=True): """Scans for supported UDS services on the specified arbitration ID. Returns a list of found service IDs. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param timeout: delay between each request sent :param min_id: first service ID to scan :param max_id: last service ID to scan :param print_results: whether progress should be printed to stdout :type arb_id_request: int :type arb_id_response: int :type timeout: float :type min_id: int :type max_id: int :type print_results: bool :return: list of supported service IDs :rtype [int] """ found_services = [] with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) # Send requests try: for service_id in range(min_id, max_id + 1): tp.send_request([service_id]) if print_results: print("\rProbing service 0x{0:02x} ({0}/{1}): found {2}" .format(service_id, max_id, len(found_services)), end="") stdout.flush() # Get response msg = tp.bus.recv(timeout) if msg is None: # No response received continue # Parse response if len(msg.data) > 3: # Since service ID is included in the response, mapping is correct even if response is delayed response_id = msg.data[1] response_service_id = msg.data[2] status = msg.data[3] if response_id != Constants.NR_SI: request_id = Iso14229_1.get_service_request_id(response_id) found_services.append(request_id) elif status != NegativeResponseCodes.SERVICE_NOT_SUPPORTED: # Any other response than "service not supported" counts found_services.append(response_service_id) if print_results: print("\nDone!\n") except KeyboardInterrupt: if print_results: print("\nInterrupted by user!\n") return found_services def __service_discovery_wrapper(args): """Wrapper used to initiate a service discovery scan""" arb_id_request = args.src arb_id_response = args.dst timeout = args.timeout # Probe services found_services = service_discovery(arb_id_request, arb_id_response, timeout) # Print results for service_id in found_services: service_name = UDS_SERVICE_NAMES.get(service_id, "Unknown service") print("Supported service 0x{0:02x}: {1}" .format(service_id, service_name)) def sub_discovery(arb_id_request, arb_id_response, diagnostic, service, timeout, print_results=True): """Scans for supported UDS Diagnostic Session Control subservices on the specified arbitration ID. Returns a list of found Diagnostic Session Control subservice IDs. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param timeout: delay between each request sent :param diagnostic: the diagnostic session control subfunction in which the target service is accessible :param service: the target service to be enumerated :param print_results: whether progress should be printed to stdout :type arb_id_request: int :type arb_id_response: int :type timeout: float :type diagnostic: int :type service: int :type print_results: bool :return: list of supported service IDs :rtype [int] """ found_subservices = [] subservice_status = [] try: for i in range(0, 256): if service != Services.DiagnosticSessionControl: extended_session(arb_id_request, arb_id_response, diagnostic) else: extended_session(arb_id_request, arb_id_response, 1) time.sleep(0.1) response = raw_send(arb_id_request, arb_id_response, service, i) service_name = UDS_SERVICE_NAMES.get(service, "Unknown service") print("\rProbing sub-service ID 0x{0:02x} for service {1} (0x{2:02x}).".format(i, service_name, service), end="") if response is None: # No response received continue # Parse response if len(response) >= 2: response_id = response[0] response_service_id = response[1] if len(response) >= 3: status = response[2] else: status = None if Iso14229_1.is_positive_response(response): found_subservices.append(i) subservice_status.append(0x00) elif response_id == Constants.NR_SI and response_service_id == service and status != NegativeResponseCodes.SUB_FUNCTION_NOT_SUPPORTED: # Any other response than "service not supported" counts found_subservices.append(i) subservice_status.append(response_service_id) time.sleep(timeout) except KeyboardInterrupt: if print_results: print("\nInterrupted by user!\n") return found_subservices, subservice_status def __sub_discovery_wrapper(args): """Wrapper used to initiate a subservice discovery scan""" arb_id_request = args.src arb_id_response = args.dst diagnostic = args.dsc service = args.service timeout = args.timeout # Probe subservices found_subservices, subservice_status = sub_discovery(arb_id_request, arb_id_response, diagnostic, service, timeout) service_name = UDS_SERVICE_NAMES.get(service, "Unknown service") # Print results if len(found_subservices) == 0: print("\nNo Sub-Services were discovered for service {0:02x} - {1}.\n".format(service, service_name, end=' ')) else: print("\nSub-Services Discovered for Service {0:02x} - {1}:\n".format(service, service_name, end=' ')) for subservice_id in found_subservices: nrc_description = NRC_NAMES.get(subservice_status[found_subservices.index(subservice_id)]) print("\n0x{0:02x} : {1}".format(subservice_id, nrc_description), end=' ') def raw_send(arb_id_request, arb_id_response, service, session_type): with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages request = [0] * 2 request[0] = service request[1] = session_type tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: tp.send_request(request) response = uds.receive_response(Iso14229_1.P3_CLIENT) return response def tester_present(arb_id_request, delay, duration, suppress_positive_response): """Sends TesterPresent messages to 'arb_id_request'. Stops automatically after 'duration' seconds or runs forever if this is None. :param arb_id_request: arbitration ID for requests :param delay: seconds between each request :param duration: seconds before automatically stopping, or None to continue forever :param suppress_positive_response: whether positive responses should be suppressed :type arb_id_request: int :type delay: float :type duration: float or None :type suppress_positive_response: bool """ # SPR simply tells the recipient not to send a positive response to # each TesterPresent message if suppress_positive_response: sub_function = 0x80 else: sub_function = 0x00 # Calculate end timestamp if the TesterPresent should automatically # stop after a given duration auto_stop = duration is not None end_time = None if auto_stop: end_time = (datetime.datetime.now() + datetime.timedelta(seconds=duration)) service_id = Services.TesterPresent.service_id message_data = [service_id, sub_function] print("Sending TesterPresent to arbitration ID {0} (0x{0:02x})" .format(arb_id_request)) print("\nPress Ctrl+C to stop\n") with IsoTp(arb_id_request, None) as can_wrap: counter = 1 while True: can_wrap.send_request(message_data) print("\rCounter:", counter, end="") stdout.flush() time.sleep(delay) counter += 1 if auto_stop and datetime.datetime.now() >= end_time: break def __tester_present_wrapper(args): """Wrapper used to initiate a TesterPresent session""" arb_id_request = args.src delay = args.delay duration = args.duration suppress_positive_response = args.spr tester_present(arb_id_request, delay, duration, suppress_positive_response) def ecu_reset(arb_id_request, arb_id_response, reset_type, timeout): """Sends an ECU Reset message to 'arb_id_request'. Returns the first response received from 'arb_id_response' within 'timeout' seconds or None otherwise. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param reset_type: value corresponding to a reset type :param timeout: seconds to wait for response before timeout, or None for default UDS timeout :type arb_id_request: int :type arb_id_response int :type reset_type: int :type timeout: float or None :return: list of response byte values on success, None otherwise :rtype [int] or None """ # Sanity checks if not BYTE_MIN <= reset_type <= BYTE_MAX: raise ValueError("reset type must be within interval " "0x{0:02x}-0x{1:02x}" .format(BYTE_MIN, BYTE_MAX)) if isinstance(timeout, float) and timeout < 0.0: raise ValueError("timeout value ({0}) cannot be negative" .format(timeout)) with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: # Set timeout if timeout is not None: uds.P3_CLIENT = timeout response = uds.ecu_reset(reset_type=reset_type) return response def __ecu_reset_wrapper(args): """Wrapper used to initiate ECU Reset""" arb_id_request = args.src arb_id_response = args.dst reset_type = args.reset_type timeout = args.timeout print("Sending ECU reset, type 0x{0:02x} to arbitration ID {1} " "(0x{1:02x})".format(reset_type, arb_id_request)) try: response = ecu_reset(arb_id_request, arb_id_response, reset_type, timeout) except ValueError as e: print("ValueError: {0}".format(e)) return # Decode response if response is None: print("No response was received") else: response_length = len(response) if response_length == 0: # Empty response print("Received empty response") elif response_length == 1: # Invalid response length print("Received response [{0:02x}] (1 byte), expected at least " "2 bytes".format(response[0], len(response))) elif Iso14229_1.is_positive_response(response): # Positive response handling response_service_id = response[0] subfunction = response[1] expected_response_id = \ Iso14229_1.get_service_response_id( Services.EcuReset.service_id) if (response_service_id == expected_response_id and subfunction == reset_type): # Positive response pos_msg = "Received positive response" if response_length > 2: # Additional data can be seconds left to reset # (powerDownTime) or manufacturer specific additional_data = list_to_hex_str(response[2:], ",") pos_msg += (" with additional data: [{0}]" .format(additional_data)) print(pos_msg) else: # Service and/or subfunction mismatch print("Response service ID 0x{0:02x} and subfunction " "0x{1:02x} do not match expected values 0x{2:02x} " "and 0x{3:02x}".format(response_service_id, subfunction, Services.EcuReset.service_id, reset_type)) else: # Negative response handling print_negative_response(response) def print_negative_response(response): """ Helper function for decoding and printing a negative response received from a UDS server. :param response: Response data after CAN-TP layer has been removed :type response: [int] :return: Nothing """ nrc = response[2] nrc_description = NRC_NAMES.get(nrc, "Unknown NRC value") print("Received negative response code (NRC) 0x{0:02x}: {1}" .format(nrc, nrc_description)) def __security_seed_wrapper(args): """Wrapper used to initiate security seed dump""" arb_id_request = args.src arb_id_response = args.dst reset_type = args.reset session_type = args.sess_type level = args.sec_level num_seeds = args.num reset_delay = args.delay seed_list = [] try: print("Security seed dump started. Press Ctrl+C to stop.\n") while num_seeds > len(seed_list) or num_seeds == 0: # Extended diagnostics response = extended_session(arb_id_request, arb_id_response, session_type) if not Iso14229_1.is_positive_response(response): print("Unable to enter extended session. Retrying...\n") continue # Request seed response = request_seed(arb_id_request, arb_id_response, level, None, None) if response is None: print("\nInvalid response") elif Iso14229_1.is_positive_response(response): seed_list.append(list_to_hex_str(response[2:])) print("Seed received: {}\t(Total captured: {})" .format(list_to_hex_str(response[2:]), len(seed_list)), end="\r") stdout.flush() else: print_negative_response(response) break if reset_type: ecu_reset(arb_id_request, arb_id_response, reset_type, None) time.sleep(reset_delay) except KeyboardInterrupt: print("Interrupted by user.") except ValueError as e: print(e) return if len(seed_list) > 0: print("\n") print("Security Access Seeds captured:") for seed in seed_list: print(seed) def extended_session(arb_id_request, arb_id_response, session_type): with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: response = uds.diagnostic_session_control(session_type) return response def request_seed(arb_id_request, arb_id_response, level, data_record, timeout): """Sends an Request seed message to 'arb_id_request'. Returns the first response received from 'arb_id_response' within 'timeout' seconds or None otherwise. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param level: vehicle manufacturer specific access level to request seed for :param data_record: optional vehicle manufacturer specific data to transmit when requesting seed :param timeout: seconds to wait for response before timeout, or None for default UDS timeout :type arb_id_request: int :type arb_id_response: int :type level: int :type data_record: [int] or None :type timeout: float or None :return: list of response byte values on success, None otherwise :rtype [int] or None """ # Sanity checks if (not Services.SecurityAccess.RequestSeedOrSendKey() .is_valid_request_seed_level(level)): raise ValueError("Invalid request seed level") if isinstance(timeout, float) and timeout < 0.0: raise ValueError("Timeout value ({0}) cannot be negative" .format(timeout)) with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: # Set timeout if timeout is not None: uds.P3_CLIENT = timeout response = uds.security_access_request_seed(level, data_record) return response def send_key(arb_id_request, arb_id_response, level, key, timeout): """ Sends a Send key message to 'arb_id_request'. Returns the first response received from 'arb_id_response' within 'timeout' seconds or None otherwise. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param level: vehicle manufacturer specific access level to send key for :param key: key to transmit :param timeout: seconds to wait for response before timeout, or None for default UDS timeout :type arb_id_request: int :type arb_id_response: int :type level: int :type key: [int] :type timeout: float or None :return: list of response byte values on success, None otherwise :rtype [int] or None """ # Sanity checks if (not Services.SecurityAccess.RequestSeedOrSendKey() .is_valid_send_key_level(level)): raise ValueError("Invalid send key level") if isinstance(timeout, float) and timeout < 0.0: raise ValueError("Timeout value ({0}) cannot be negative" .format(timeout)) with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: # Set timeout if timeout is not None: uds.P3_CLIENT = timeout response = uds.security_access_send_key(level=level, key=key) return response def __dump_dids_wrapper(args): """Wrapper used to initiate data identifier dump""" arb_id_request = args.src arb_id_response = args.dst timeout = args.timeout min_did = args.min_did max_did = args.max_did print_results = True dump_dids(arb_id_request, arb_id_response, timeout, min_did, max_did, print_results) def __auto_wrapper(args): """Wrapper used to initiate automated UDS scan""" min_id = args.min max_id = args.max blacklist = args.blacklist auto_blacklist_duration = args.autoblacklist delay = args.delay verify = not args.skipverify print_results = True timeout = args.timeout min_did = args.min_did max_did = args.max_did try: arb_id_pairs = uds_discovery(min_id, max_id, blacklist, auto_blacklist_duration, delay, verify, print_results) print("\n") if len(arb_id_pairs) == 0: # No UDS discovered print("\nDiagnostics service could not be found.") else: # Print result table print("\nIdentified diagnostics:\n") table_line = "+------------+------------+" print(table_line) print("| CLIENT ID | SERVER ID |") print(table_line) for (client_id, server_id) in arb_id_pairs: print("| 0x{0:08x} | 0x{1:08x} |" .format(client_id, server_id)) print(table_line) print("\n") # Enumerate each pair for (client_id, server_id) in arb_id_pairs: args.src = client_id args.dst = server_id # Print Client/Server result table print("\nTarget Diagnostic IDs:\n") table_line = "+------------+------------+" print(table_line) print("| CLIENT ID | SERVER ID |") print(table_line) print("| 0x{0:08x} | 0x{1:08x} |" .format(client_id, server_id)) print(table_line) print("\nEnumerating Services:\n") found_services = service_discovery(client_id, server_id, timeout) found_subservices = [] print("\nIdentified services:\n") # Print available services result table for service_id in found_services: service_name = UDS_SERVICE_NAMES.get(service_id, "Unknown service") print("Supported service 0x{0:02x}: {1}" .format(service_id, service_name)) print("\n") dump_dids(client_id, server_id, timeout, min_did, max_did, print_results) if ServiceID.DIAGNOSTIC_SESSION_CONTROL in found_services: print("\nEnumerating Diagnostic Session Control Service:\n") found_subservices = [] subservice_status = [] for i in range(1, 256): extended_session(client_id, server_id, 1) response = extended_session(client_id, server_id, i) print("\rProbing diagnostic session control sub-service 0x{0:02x}".format(i), end="") if response is None: # No response received continue # Parse response if len(response) >= 3: response_id = response[0] response_service_id = response[1] status = response[2] if Iso14229_1.is_positive_response(response): found_subservices.append(i) subservice_status.append(0x00) elif response_id == Constants.NR_SI and response_service_id == 0x10 and status != NegativeResponseCodes.SUB_FUNCTION_NOT_SUPPORTED: # Any other response than "service not supported" counts found_subservices.append(i) subservice_status.append(response_service_id) time.sleep(timeout) # Print results if len(found_subservices) == 0: print("\nNo Diagnostic Session Control Sub-Services were discovered\n", end=' ') else: print("\n") print("\nDiscovered Diagnostic Session Control Sub-Services:\n", end=' ') for subservice_id in found_subservices: nrc_description = NRC_NAMES.get(subservice_status[found_subservices.index(subservice_id)]) print("\n0x{0:02x} : {1}".format(subservice_id, nrc_description), end=' ') if ServiceID.ECU_RESET in found_services: print("\n") print("\nEnumerating ECUReset Service:\n") found_subservices = [] subservice_status = [] for i in range(1, 5): extended_session(client_id, server_id, 3) response = raw_send(client_id, server_id, 17, i) print("\rProbing ECUReset sub-service 0x{0:02x}".format(i), end="") if response is None: # No response received continue # Parse response if len(response) >= 2: response_id = response[0] response_service_id = response[1] if len(response) >= 3: status = response[2] else: status = None if Iso14229_1.is_positive_response(response): found_subservices.append(i) subservice_status.append(0x00) elif response_id == Constants.NR_SI and response_service_id == 0x11 and status != NegativeResponseCodes.SUB_FUNCTION_NOT_SUPPORTED: # Any other response than "service not supported" counts found_subservices.append(i) subservice_status.append(response_service_id) time.sleep(timeout) # Print results if len(found_subservices) == 0: print("\nNo ECUReset Sub-Services were discovered.\n", end=' ') else: print("\n") print("\nDiscovered ECUReset Sub-Services:\n", end=' ') for subservice_id in found_subservices: nrc_description = NRC_NAMES.get(subservice_status[found_subservices.index(subservice_id)]) print("\n0x{0:02x} : {1}".format(subservice_id, nrc_description), end=' ') if ServiceID.SECURITY_ACCESS in found_services: found_subdiag = [] found_subsec = [] print("\n") for subservice_id in found_subservices: for level in range(1, 256): print( "\rProbing security access sub-service 0x{0:02x} in diagnostic session 0x{1:02x}.".format( level, subservice_id), end=" ") extended_session(client_id, server_id, 1) extended_session(client_id, server_id, subservice_id) response = raw_send(client_id, server_id, 39, level) if response is None: continue elif Iso14229_1.is_positive_response(response): found_subdiag.append(subservice_id) found_subsec.append(level) if len(found_subsec) == 0: print("\nNo Security Access Sub-Services were discovered.\n") else: print("\n") print("\nDiscovered Security Access Sub Services:\n") print("\n") table_line_sec = "+----------------------+-------------------+" print(table_line_sec) print("| Diagnostic Session | Security Access |") print(table_line_sec) for counter in range(len(found_subsec)): diag = found_subdiag[counter] sec = found_subsec[counter] print("| 0x{0:02x} | 0x{1:02x} |" .format(diag, sec)) counter += 1 print(table_line_sec) except ValueError as e: print("\nDiscovery failed: {0}".format(e), end=" ") def dump_dids(arb_id_request, arb_id_response, timeout, min_did=DUMP_DID_MIN, max_did=DUMP_DID_MAX, print_results=True): """ Sends read data by identifier (DID) messages to 'arb_id_request'. Returns a list of positive responses received from 'arb_id_response' within 'timeout' seconds or an empty list if no positive responses were received. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param timeout: seconds to wait for response before timeout, or None for default UDS timeout :param min_did: minimum device identifier to read :param max_did: maximum device identifier to read :param print_results: whether progress should be printed to stdout :type arb_id_request: int :type arb_id_response: int :type timeout: float or None :type min_did: int :type max_did: int :type print_results: bool :return: list of tuples containing DID and response bytes on success, empty list if no responses :rtype [(int, [int])] or [] """ # Sanity checks if isinstance(timeout, float) and timeout < 0.0: raise ValueError("Timeout value ({0}) cannot be negative" .format(timeout)) if max_did < min_did: raise ValueError("max_did must not be smaller than min_did -" " got min:0x{0:x}, max:0x{1:x}".format(min_did, max_did)) responses = [] with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: # Set timeout if timeout is not None: uds.P3_CLIENT = timeout if print_results: print('Dumping DIDs in range 0x{:04x}-0x{:04x}\n'.format( min_did, max_did)) print('Identified DIDs:') print('DID Value (hex)') for identifier in range(min_did, max_did + 1): response = uds.read_data_by_identifier(identifier=[identifier]) # Only keep positive responses if response and Iso14229_1.is_positive_response(response): responses.append((identifier, response)) if print_results: print('0x{:04x}'.format(identifier), list_to_hex_str(response)) if print_results: print("\nDone!") return responses def __parse_args(args): """Parser for module arguments""" parser = argparse.ArgumentParser( prog="cc.py uds", formatter_class=argparse.RawDescriptionHelpFormatter, description="Universal Diagnostic Services module for " "CaringCaribou", epilog="""Example usage: cc.py uds discovery cc.py uds discovery -blacklist 0x123 0x456 cc.py uds discovery -autoblacklist 10 cc.py uds services 0x733 0x633 cc.py uds ecu_reset 1 0x733 0x633 cc.py uds testerpresent 0x733 cc.py uds security_seed 0x3 0x1 0x733 0x633 -r 1 -d 0.5 cc.py uds dump_dids 0x733 0x633 cc.py uds dump_dids 0x733 0x633 --min_did 0x6300 --max_did 0x6fff -t 0.1""") subparsers = parser.add_subparsers(dest="module_function") subparsers.required = True # Parser for diagnostics discovery parser_discovery = subparsers.add_parser("discovery") parser_discovery.add_argument("-min", type=parse_int_dec_or_hex, default=None, help="min arbitration ID " "to send request for") parser_discovery.add_argument("-max", type=parse_int_dec_or_hex, default=None, help="max arbitration ID " "to send request for") parser_discovery.add_argument("-b", "--blacklist", metavar="B", type=parse_int_dec_or_hex, default=[], nargs="+", help="arbitration IDs to blacklist " "responses from") parser_discovery.add_argument("-ab", "--autoblacklist", metavar="N", type=float, default=0, help="listen for false positives for N seconds " "and blacklist matching arbitration " "IDs before running discovery") parser_discovery.add_argument("-sv", "--skipverify", action="store_true", help="skip verification step (reduces " "result accuracy)") parser_discovery.add_argument("-d", "--delay", metavar="D", type=float, default=DELAY_DISCOVERY, help="D seconds delay between messages " "(default: {0})".format(DELAY_DISCOVERY)) parser_discovery.set_defaults(func=__uds_discovery_wrapper) # Parser for diagnostics service discovery parser_info = subparsers.add_parser("services") parser_info.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_info.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_info.add_argument("-t", "--timeout", metavar="T", type=float, default=TIMEOUT_SERVICES, help="wait T seconds for response before " "timeout (default: {0})" .format(TIMEOUT_SERVICES)) parser_info.set_defaults(func=__service_discovery_wrapper) # Parser for diagnostics session control subservice discovery parser_sub = subparsers.add_parser("subservices") parser_sub.add_argument("dsc", metavar="dtype", type=parse_int_dec_or_hex, default="0x01", help="Diagnostic Session Control Subsession Byte") parser_sub.add_argument("service", metavar="stype", type=parse_int_dec_or_hex, help="Service ID") parser_sub.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_sub.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_sub.add_argument("-t", "--timeout", metavar="T", type=float, default=TIMEOUT_SUBSERVICES, help="wait T seconds for response before " "timeout (default: {0})" .format(TIMEOUT_SUBSERVICES)) parser_sub.set_defaults(func=__sub_discovery_wrapper) # Parser for ECU Reset parser_ecu_reset = subparsers.add_parser("ecu_reset") parser_ecu_reset.add_argument("reset_type", metavar="type", type=parse_int_dec_or_hex, help="Reset type: 1=hard, 2=key off/on, " "3=soft, " "4=enable rapid power shutdown, " "5=disable rapid power shutdown") parser_ecu_reset.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_ecu_reset.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_ecu_reset.add_argument("-t", "--timeout", type=float, metavar="T", help="wait T seconds for response before " "timeout") parser_ecu_reset.set_defaults(func=__ecu_reset_wrapper) # Parser for TesterPresent parser_tp = subparsers.add_parser("testerpresent") parser_tp.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_tp.add_argument("-d", "--delay", metavar="D", type=float, default=DELAY_TESTER_PRESENT, help="send TesterPresent every D seconds " "(default: {0})".format(DELAY_TESTER_PRESENT)) parser_tp.add_argument("-dur", "--duration", metavar="S", type=float, help="automatically stop after S seconds") parser_tp.add_argument("-spr", action="store_true", help="suppress positive response") parser_tp.set_defaults(func=__tester_present_wrapper) # Parser for SecuritySeedDump parser_secseed = subparsers.add_parser("security_seed") parser_secseed.add_argument("sess_type", metavar="stype", type=parse_int_dec_or_hex, help="Session Type: 1=defaultSession " "2=programmingSession 3=extendedSession " "4=safetySession [0x40-0x5F]=OEM " "[0x60-0x7E]=Supplier " "[0x0, 0x5-0x3F, 0x7F]=ISOSAEReserved") parser_secseed.add_argument("sec_level", metavar="level", type=parse_int_dec_or_hex, help="Security level: " "[0x1-0x41 (odd only)]=OEM " "0x5F=EOLPyrotechnics " "[0x61-0x7E]=Supplier " "[0x0, 0x43-0x5E, 0x7F]=ISOSAEReserved") parser_secseed.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_secseed.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_secseed.add_argument("-r", "--reset", metavar="RTYPE", type=parse_int_dec_or_hex, help="Enable reset between security seed " "requests. Valid RTYPE integers are: " "1=hardReset, 2=key off/on, 3=softReset, " "4=enable rapid power shutdown, " "5=disable rapid power shutdown. " "(default: None)") parser_secseed.add_argument("-d", "--delay", metavar="D", type=float, default=DELAY_SECSEED_RESET, help="Wait D seconds between reset and " "security seed request. You'll likely " "need to increase this when using RTYPE: " "1=hardReset. Does nothing if RTYPE " "is None. (default: {0})" .format(DELAY_SECSEED_RESET)) parser_secseed.add_argument("-n", "--num", metavar="NUM", default=0, type=parse_int_dec_or_hex, help="Specify a positive number of security" " seeds to capture before terminating. " "A '0' is interpreted as infinity. " "(default: 0)") parser_secseed.set_defaults(func=__security_seed_wrapper) # Parser for dump_did parser_did = subparsers.add_parser("dump_dids") parser_did.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_did.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_did.add_argument("-t", "--timeout", type=float, metavar="T", default=DUMP_DID_TIMEOUT, help="wait T seconds for response before " "timeout") parser_did.add_argument("--min_did", type=parse_int_dec_or_hex, default=DUMP_DID_MIN, help="minimum device identifier (DID) to read (default: 0x0000)") parser_did.add_argument("--max_did", type=parse_int_dec_or_hex, default=DUMP_DID_MAX, help="maximum device identifier (DID) to read (default: 0xFFFF)") parser_did.set_defaults(func=__dump_dids_wrapper) parser_auto = subparsers.add_parser("auto") parser_auto.add_argument("-min", type=parse_int_dec_or_hex, default=None, help="min arbitration ID " "to send request for") parser_auto.add_argument("-max", type=parse_int_dec_or_hex, default=None, help="max arbitration ID " "to send request for") parser_auto.add_argument("-b", "--blacklist", metavar="B", type=parse_int_dec_or_hex, default=[], nargs="+", help="arbitration IDs to blacklist " "responses from") parser_auto.add_argument("-ab", "--autoblacklist", metavar="N", type=float, default=0, help="listen for false positives for N seconds " "and blacklist matching arbitration " "IDs before running discovery") parser_auto.add_argument("-sv", "--skipverify", action="store_true", help="skip verification step (reduces " "result accuracy)") parser_auto.add_argument("-d", "--delay", metavar="D", type=float, default=DELAY_DISCOVERY, help="D seconds delay between messages " "(default: {0})".format(DELAY_DISCOVERY)) parser_auto.add_argument("-t", "--timeout", metavar="T", type=float, default=TIMEOUT_SERVICES, help="wait T seconds for response before " "timeout (default: {0})" .format(TIMEOUT_SERVICES)) parser_auto.add_argument("--min_did", type=parse_int_dec_or_hex, default=DUMP_DID_MIN, help="minimum device identifier (DID) to read (default: 0x0000)") parser_auto.add_argument("--max_did", type=parse_int_dec_or_hex, default=DUMP_DID_MAX, help="maximum device identifier (DID) to read (default: 0xFFFF)") parser_auto.set_defaults(func=__auto_wrapper) args = parser.parse_args(args) return args def module_main(arg_list): """Module main wrapper""" try: args = __parse_args(arg_list) args.func(args) except KeyboardInterrupt: print("\n\nTerminated by user")
58,081
42.637866
159
py
caringcaribou
caringcaribou-master/caringcaribou/modules/uds_fuzz.py
from __future__ import print_function from caringcaribou.utils.common import list_to_hex_str, parse_int_dec_or_hex, str_to_int_list from caringcaribou.utils.iso14229_1 import Iso14229_1 from caringcaribou.modules.uds import ecu_reset, print_negative_response, request_seed, extended_session from sys import stdout import argparse import time # Number of seconds to wait between messages DELAY_SECSEED_RESET = 0.011 DELAY_FUZZ_RESET = 3.901 # Message data length limits MIN_DATA_LENGTH = 1 MAX_DATA_LENGTH = 8 # Max size of random seed if no seed is provided in arguments DEFAULT_SEED_MAX = 2 ** 16 # Number of sub-lists to split message list into per round in 'replay' mode REPLAY_NUMBER_OF_SUB_LISTS = 5 BYTE_MIN = 0x00 BYTE_MAX = 0xFF # Duplicate testing from https://www.iditect.com/guide/python/python_howto_find_the_duplicates_in_a_list.html def find_duplicates(sequence): first_seen = set() first_seen_add = first_seen.add duplicates = set(i for i in sequence if i in first_seen or first_seen_add(i)) return duplicates def seed_randomness_fuzzer(args): """Wrapper used to initiate security randomness fuzzer""" arb_id_request = args.src arb_id_response = args.dst reset_type = args.reset session_type = args.sess_type iterations = args.iter reset_delay = args.delay reset_method = args.reset_method inter = args.inter_delay seed_list = [] try: # Issue first reset with the supplied delay time print("Security seed dump started. Press Ctrl+C if you need to stop.\n") ecu_reset(arb_id_request, arb_id_response, reset_type, None) time.sleep(reset_delay) for i in range(iterations): if reset_method == 1 and i > 0: ecu_reset(arb_id_request, arb_id_response, reset_type, None) time.sleep(reset_delay) for y in range(0, len(session_type), 4): # Get into the appropriate supplied session if session_type[y] == "1" and session_type[y + 1] == "0": session = str_to_hex(y, session_type) response = extended_session(arb_id_request, arb_id_response, session) if not Iso14229_1.is_positive_response(response): print("Unable to enter session. Retrying...\n") if inter: time.sleep(inter) # Request seed elif session_type[y] == "2" and session_type[y + 1] == "7": session = str_to_hex(y, session_type) response = request_seed(arb_id_request, arb_id_response, session, None, None) if response is None: print("\nInvalid response") elif Iso14229_1.is_positive_response(response): seed_list.append(list_to_hex_str(response[2:])) print("Seed received: {}\t(Total captured: {})" .format(list_to_hex_str(response[2:]), len(seed_list)), end="\r") stdout.flush() if inter: time.sleep(inter) else: print_negative_response(response) break # ECUReset elif session_type[y] == "1" and session_type[y + 1] == "1": ecu_reset(arb_id_request, arb_id_response, int(session_type[y + 3]), None) time.sleep(reset_delay) else: print("\nPlease check your supplied sequence...") break except KeyboardInterrupt: print("Interrupted by user.") except ValueError as e: print(e) return # Print captured seeds and found duplicates if len(seed_list) > 0: print("\n") print("Security Access Seeds captured:") for seed in seed_list: print(seed) print("\nDuplicates found: \n", find_duplicates(seed_list)) def delay_fuzzer(args): """Wrapper used to initiate delay fuzzer""" arb_id_request = args.src arb_id_response = args.dst reset_type = args.reset session_type = args.sess_type target = args.target_seed reset_delay = args.delay loop = True seed_list = [] try: print("Security seed dump started. Press Ctrl+C to stop.\n") while loop: # Issue first reset with the supplied delay time ecu_reset(arb_id_request, arb_id_response, reset_type, None) time.sleep(reset_delay) # Loop through the length of the supplied input for i in range(0, len(session_type), 4): # Get into the appropriate supplied session if session_type[i] == "1" and session_type[i + 1] == "0": session = str_to_hex(i, session_type) response = extended_session(arb_id_request, arb_id_response, session) if not Iso14229_1.is_positive_response(response): print("Unable to enter session. Retrying...\n") break # Request seed elif session_type[i] == "2" and session_type[i + 1] == "7": session = str_to_hex(i, session_type) response = request_seed(arb_id_request, arb_id_response, session, None, None) if response is None: print("\nInvalid response") elif Iso14229_1.is_positive_response(response): seed_list.append(list_to_hex_str(response[2:])) print("Seed received: {}\t(Total captured: {}, Delay used: {})" .format(list_to_hex_str(response[2:]), len(seed_list), reset_delay), end="\r") if list_to_hex_str(response[2:]) == list_to_hex_str(str_to_int_list(target)): print("\n\nTarget seed found with delay: ", reset_delay) loop = False break stdout.flush() else: print_negative_response(response) break # ECUReset elif session_type[i] == 1 and session_type[i + 1] == 1: ecu_reset(arb_id_request, arb_id_response, reset_type, None) time.sleep(reset_delay) else: break # ECUReset and increase of delay in each loop if reset_type: ecu_reset(arb_id_request, arb_id_response, reset_type, None) time.sleep(reset_delay) reset_delay += 0.001 except KeyboardInterrupt: print("Interrupted by user.") except ValueError as e: print(e) return if len(seed_list) > 0: print("\n") print("Security Access Seeds captured:") for seed in seed_list: print(seed) def str_to_hex(i, session_type): max_index = i + 3 if len(session_type) >= max_index: session = [] session.append('0x') session.append(session_type[i + 2]) session.append(session_type[i + 3]) session = ''.join(session) session = int(session, 16) return session else: return def __parse_args(args): """Parser for module arguments""" parser = argparse.ArgumentParser( prog="cc.py uds_fuzz", formatter_class=argparse.RawDescriptionHelpFormatter, description="UDS seed randomness fuzzer and tester module for " "CaringCaribou", epilog="""Example usage: cc.py uds_fuzz seed_randomness_fuzzer 100311022701 0x733 0x633 -d 4 -r 1 -id 2 -m 0 cc.py uds_fuzz delay_fuzzer 100311022701 0x03 0x733 0x633""") subparsers = parser.add_subparsers(dest="module_function") subparsers.required = True # Parser for Delay fuzz testing parser_delay_fuzzer = subparsers.add_parser("delay_fuzzer") parser_delay_fuzzer.add_argument("sess_type", metavar="stype", help="Describe the session sequence followed by " "the target ECU." "e.g. if the following sequence is needed in order to request a seed: " "Request 1 - 1003 (Diagnostic Session Control), " "Request 2 - 1102 (ECUReset), " "Request 3 - 1005 (Diagnostic Session Control), " "Request 4 - 2705 (Security Access Seed Request). " "The option should be: 1003110210052705\n") parser_delay_fuzzer.add_argument("target_seed", metavar="target", help="Seed that is targeted for the delay attack. " "e.g. 41414141414141") parser_delay_fuzzer.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_delay_fuzzer.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_delay_fuzzer.add_argument("-r", "--reset", metavar="RTYPE", default=1, type=parse_int_dec_or_hex, help="Enable reset between security seed " "requests. Valid RTYPE integers are: " "1=hardReset, 2=key off/on, 3=softReset, " "4=enable rapid power shutdown, " "5=disable rapid power shutdown. " "This attack is based on hard ECUReset (1) " "as it targets seed randomness based on " "the system clock. (default: hardReset)") parser_delay_fuzzer.add_argument("-d", "--delay", metavar="D", type=float, default=DELAY_SECSEED_RESET, help="Wait D seconds between the different " "iterations of security seed request. You'll " "likely need to increase this when using RTYPE: " "1=hardReset. (default: {0})" .format(DELAY_SECSEED_RESET)) parser_delay_fuzzer.set_defaults(func=delay_fuzzer) # Parser for Delay fuzz testing parser_randomness_fuzzer = subparsers.add_parser("seed_randomness_fuzzer") parser_randomness_fuzzer.add_argument("sess_type", metavar="stype", help="Describe the session sequence followed by " "the target ECU." "e.g. if the following sequence is needed in order to request a seed: " "Request 1 - 1003 (Diagnostic Session Control), " "Request 2 - 1102 (ECUReset), " "Request 3 - 1005 (Diagnostic Session Control), " "Request 4 - 2705 (Security Access Seed Request). " "The option should be: 1003110210052705\n") parser_randomness_fuzzer.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_randomness_fuzzer.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_randomness_fuzzer.add_argument("-t", "--iter", metavar="ITERATIONS", default=1000, type=parse_int_dec_or_hex, help="Number of iterations of seed requests. " "It is highly suggested to perform >=1000 " "for accurate results. " "(default: 1000)") parser_randomness_fuzzer.add_argument("-r", "--reset", metavar="RTYPE", default=1, type=parse_int_dec_or_hex, help="Enable reset between security seed " "requests. Valid RTYPE integers are: " "1=hardReset, 2=key off/on, 3=softReset, " "4=enable rapid power shutdown, " "5=disable rapid power shutdown. " "This attack is based on hard ECUReset (1) " "as it targets seed randomness based on " "the system clock. (default: hardReset)") parser_randomness_fuzzer.add_argument("-id", "--inter_delay", metavar="RTYPE", default=0.1, type=float, help="Intermediate delay between messages:" "(default: 0.1)") parser_randomness_fuzzer.add_argument("-m", "--reset_method", metavar="RMETHOD", default=1, type=parse_int_dec_or_hex, help="The method that the ECUReset will happen: " "1=before each seed request " "0=once before the seed requests start " "(default: 1) *This method works better with option 1.*") parser_randomness_fuzzer.add_argument("-d", "--delay", metavar="D", type=float, default=DELAY_SECSEED_RESET, help="Wait D seconds between reset and " "security seed request. You'll likely " "need to increase this when using RTYPE: " "1=hardReset. Does nothing if RTYPE " "is None. (default: {0})" .format(DELAY_FUZZ_RESET)) parser_randomness_fuzzer.set_defaults(func=seed_randomness_fuzzer) args = parser.parse_args(args) return args def module_main(arg_list): """Module main wrapper""" try: args = __parse_args(arg_list) args.func(args) except KeyboardInterrupt: print("\n\nTerminated by user")
15,686
47.119632
118
py
caringcaribou
caringcaribou-master/caringcaribou/modules/__init__.py
0
0
0
py
caringcaribou
caringcaribou-master/caringcaribou/modules/xcp.py
from __future__ import print_function from caringcaribou.utils.can_actions import CanActions, auto_blacklist from caringcaribou.utils.common import list_to_hex_str, parse_int_dec_or_hex from datetime import datetime, timedelta from sys import stdout import argparse import time # Dictionary of XCP error codes XCP_ERROR_CODES = { 0x00: ("ERR_CMD_SYNC", "Command processor synchronisation."), 0x10: ("ERR_CMD_BUSY", "Command was not executed."), 0x11: ("ERR_DAQ_ACTIVE", "Command rejected because DAQ is running."), 0x12: ("ERR_PGM_ACTIVE", "Command rejected because PGM is running."), 0x20: ("ERR_CMD_UNKNOWN", "Unknown command or not implemented optional command."), 0x21: ("ERR_CMD_SYNTAX", "Command syntax invalid."), 0x22: ("ERR_OUT_OF_RANGE", "Command syntax valid but command parameter(s) out of range."), 0x23: ("ERR_WRITE_PROTECTED", "The memory location is write protected."), 0x24: ("ERR_ACCESS_DENIED", "The memory location is not accessible."), 0x25: ("ERR_ACCESS_LOCKED", "Access denied, Seed & Key is required."), 0x26: ("ERR_PAGE_NOT_VALID", "Selected page not available."), 0x27: ("ERR_MODE_NOT_VALID", "Selected page mode not available."), 0x28: ("ERR_SEGMENT_NOT_VALID", "Selected segment not valid."), 0x29: ("ERR_SEQUENCE", "Sequence error."), 0x2A: ("ERR_DAQ_CONFIG", "DAQ configuration not valid."), 0x30: ("ERR_MEMORY_OVERFLOW", "Memory overflow error."), 0x31: ("ERR_GENERIC", "Generic error."), 0x32: ("ERR_VERIFY", "The slave internal program verify routine detects an error.") } # List of XCP Command codes XCP_COMMAND_CODES = [ (0xFF, "CONNECT"), (0xFE, "DISCONNECT"), (0xFD, "GET_STATUS"), (0xFC, "SYNCH"), (0xFB, "GET_COMM_MODE_INFO"), (0xFA, "GET_ID"), (0xF9, "SET_REQUEST"), (0xF8, "GET_SEED"), (0xF7, "UNLOCK"), (0xF6, "SET_MTA"), (0xF5, "UPLOAD"), (0xF4, "SHORT_UPLOAD"), (0xF3, "BUILD_CHECKSUM"), (0xF2, "TRANSPORT_LAYER_CMD"), (0xF1, "USER_CMD"), (0xF0, "DOWNLOAD"), (0xEF, "DOWNLOAD_NEXT"), (0xEE, "DOWNLOAD_MAX"), (0xED, "SHORT_DOWNLOAD"), (0xEC, "MODIFY_BITS"), (0xEB, "SET_CAL_PAGE"), (0xEA, "GET_CAL_PAGE"), (0xE9, "GET_PAG_PROCESSOR_INFO"), (0xE8, "GET_SEGMENT_INFO"), (0xE7, "GET_PAGE_INFO"), (0xE6, "SET_SEGMENT_MODE"), (0xE5, "GET_SEGMENT_MODE"), (0xE4, "COPY_CAL_PAGE"), (0xE3, "CLEAR_DAQ_LIST"), (0xE2, "SET_DAQ_PTR"), (0xE1, "WRITE_DAQ"), (0xE0, "SET_DAQ_LIST_MODE"), (0xDF, "GET_DAQ_LIST_MODE"), (0xDE, "START_STOP_DAQ_LIST"), (0xDD, "START_STOP_SYNCH"), (0xDC, "GET_DAQ_CLOCK"), (0xDB, "READ_DAQ"), (0xDA, "GET_DAQ_PROCESSOR_INFO"), (0xD9, "GET_DAQ_RESOLUTION_INFO"), (0xD8, "GET_DAQ_LIST_INFO"), (0xD7, "GET_DAQ_EVENT_INFO"), (0xD6, "FREE_DAQ"), (0xD5, "ALLOC_DAQ"), (0xD4, "ALLOC_ODT"), (0xD3, "ALLOC_ODT_ENTRY"), (0xD2, "PROGRAM_START"), (0xD1, "PROGRAM_CLEAR"), (0xD0, "PROGRAM"), (0xCF, "PROGRAM_RESET"), (0xCE, "GET_PGM_PROCESSOR_INFO"), (0xCD, "GET_SECTOR_INFO"), (0xCC, "PROGRAM_PREPARE"), (0xCB, "PROGRAM_FORMAT"), (0xCA, "PROGRAM_NEXT"), (0xC9, "PROGRAM_MAX"), (0xC8, "PROGRAM_VERIFY") ] def decode_xcp_error(error_message): """ Decodes an XCP error message and prints a short description. :param error_message: The error message """ data = error_message.data if not data[0] == 0xfe: print("Not a valid error message: {0}".format(error_message)) return error_lookup = XCP_ERROR_CODES.get(data[1], ("UNKNOWN", "Unknown error")) print("Received error message:\n{0}".format(error_message)) print("Error code (0x{0:02x}): {1}\nDescription: {2}".format(data[1], error_lookup[0], error_lookup[1])) def decode_connect_response(response_message): """ Decodes an XCP connect response and prints the response information. :param response_message: The connect response message """ print("> DECODE CONNECT RESPONSE") print(response_message) data = response_message.data if len(data) != 8: print("Invalid response length: {0} (expected: 8)".format(len(data))) return print("-" * 20) print("Resource protection status\n") # Note: sometimes referred to as RESSOURCE (sic) in specification resource_bits = ["CAL/PAG", "X (bit 1)", "DAQ", "STIM", "PGM", "X (bit 5)", "X (bit 6)", "X (bit 7)"] for i in range(8): print("{0:<12}{1}".format(resource_bits[i], bool(data[1] & 2 ** i))) print("-" * 20) print("COMM_MODE_BASIC\n") comm_mode_bits = ["BYTE_ORDER", "ADDRESS_GRANULARITY_0", "ADDRESS_GRANULARITY_1", "X (bit 3)", "X (bit 4)", "X (bit 5)", "SLAVE_BLOCK_MODE", "OPTIONAL"] for i in range(8): print("{0:<24}{1}".format(comm_mode_bits[i], int(bool(data[2] & 2 ** i)))) print("\nAddress granularity: {0} byte(s) per address".format(2 ** ((data[2] & 4) * 2 + data[2] & 2))) print("-" * 20) print("Max CTO message length: {0} bytes".format(data[3])) print("Max DTO message length: {0} bytes".format(data[5] * 16 + data[4])) print("Protocol layer version: {0}".format(data[6])) print("Transport layer version: {0}".format(data[7])) def decode_get_comm_mode_info_response(response_message): """ Decodes an XCP GET_COMM_MODE_INFO response and prints the response information. :param response_message: The response message """ print("> DECODE GET COMM MODE INFO") print(response_message) data = response_message.data print("Reserved: 0x{0:02x}".format(data[1])) print("-" * 20) print("COMM_MODE_OPTIONAL") comm_mode_optional_bits = ["MASTER_BLOCK_MODE", "INTERLEAVED_MODE"] + ["X (bit {0})".format(i) for i in range(2, 8)] for i in range(8): print("{0:<20}{1}".format(comm_mode_optional_bits[i], bool(data[2] & 2 ** i))) print("-" * 20) print("Reserved: 0x{0:02x}".format(data[3])) print("MAX_BS (master block mode): {0} command packets".format(data[4])) print("MIN_ST (minimum separation time): {0} * 100 us".format(data[5])) print("QUEUE_SIZE (interleaved mode): {0} command packets".format(data[6])) print("XCP Driver version: 0x{0:02x}".format(data[7])) def decode_get_status_response(response_message): print("> DECODE GET STATUS") print(response_message) data = response_message.data print("-" * 20) print("CURRENT_SESSION_STATUS") current_session_status_bits = ["STORE_CAL_REQ", "X (bit 1)", "STORE_DAQ_REQ", "CLEAR_DAQ_REQ", "X (bit 4)", "X (bit 5)", "DAQ_RUNNING", "RESUME"] for i in range(8): print("{0:<16}{1}".format(current_session_status_bits[i], int(bool(data[1] & 2 ** i)))) print("-" * 20) print("RESOURCE PROTECTION STATUS | Seed/key required") resource_protection_bits = ["CAL/PAG", "X (bit 1)", "DAQ", "STIM", "PGM", "X (bit 5)", "X (bit 6)", "X (bit 7)"] for i in range(8): print("{0:<27}| {1}".format(resource_protection_bits[i], bool(data[2] & 2 ** i))) print("-" * 20) print("Reserved: 0x{0:02x}".format(data[3])) print("Session configuration ID: {0}".format(2 ** ((data[5] & 4) * 2 + data[4] & 2))) def xcp_arbitration_id_discovery(args): """Scans for XCP support by brute forcing XCP connect messages against different arbitration IDs.""" global hit_counter min_id = args.min max_id = args.max blacklist = set(args.blacklist) blacklist_duration = args.autoblacklist hit_counter = 0 def is_valid_response(msg): """ Returns a bool indicating whether 'data' is a valid XCP response :param data: list of message data bytes :return: True if data is a valid XCP response, False otherwise """ data = msg.data return (len(data) > 1 and data[0] == 0xff and any(data[1:])) or \ (len(data) > 0 and data[0] == 0xfe) if blacklist_duration > 0: # Perform automatic blacklist scanning with CanActions(notifier_enabled=False) as blacklist_wrap: blacklist |= auto_blacklist(blacklist_wrap.bus, blacklist_duration, is_valid_response, True) with CanActions() as can_wrap: print("Starting XCP discovery") def response_analyser_wrapper(arb_id): print("\rSending XCP connect to 0x{0:04x}".format(arb_id), end="") stdout.flush() def response_analyser(msg): global hit_counter # Ignore blacklisted arbitration IDs if msg.arbitration_id in blacklist: return # Handle positive response if msg.data[0] == 0xff and any(msg.data[1:]): hit_counter += 1 decode_connect_response(msg) print("Found XCP at arb ID 0x{0:04x}, reply at 0x{1:04x}".format(arb_id, msg.arbitration_id)) print("#" * 20) print("\n") # Handle negative response elif msg.data[0] == 0xfe: print("\nFound XCP (with a bad reply) at arbitration ID 0x{0:03x}, reply at 0x{1:04x}".format( arb_id, msg.arbitration_id)) decode_xcp_error(msg) return response_analyser def discovery_end(s): print("\r{0}: Found {1} possible matches.".format(s, hit_counter)) can_wrap.bruteforce_arbitration_id([0xff], response_analyser_wrapper, min_id=min_id, max_id=max_id, callback_end=discovery_end) def xcp_command_discovery(args): """Attempts to call all XCP commands and lists which ones are supported.""" global connect_reply, command_reply send_arb_id = args.src rcv_arb_id = args.dst connect_message = [0xff, 0, 0, 0, 0, 0, 0, 0] def connect_callback_handler(msg): global connect_reply if msg.arbitration_id == rcv_arb_id: connect_reply = True print("XCP command discovery\n") print("COMMAND{0}SUPPORTED".format(" " * 17)) print("-" * 33) with CanActions(send_arb_id) as can_wrap: # Bruteforce against list of commands (excluding connect) for cmd_code, cmd_desc in XCP_COMMAND_CODES[1:]: # Connect connect_reply = False can_wrap.send_single_message_with_callback(connect_message, connect_callback_handler) connect_timestamp = datetime.now() while not connect_reply and datetime.now() - connect_timestamp < timedelta(seconds=3): pass if not connect_reply: print("ERROR: Connect timeout") exit() # Build message for current command cmd_msg = [cmd_code, 0, 0, 0, 0, 0, 0, 0] # Callback handler for current command def callback_handler(msg): global command_reply if msg.arbitration_id == rcv_arb_id: print("{0:<23} {1}".format(cmd_desc, msg.data[0] != 0xfe)) command_reply = True command_reply = False # Send, wait for reply, clear listeners and move on can_wrap.send_single_message_with_callback(cmd_msg, callback=callback_handler) command_timestamp = datetime.now() while not command_reply and datetime.now() - command_timestamp < timedelta(seconds=3): pass if not command_reply: print("ERROR: Command timeout") exit() can_wrap.clear_listeners() print("\nDone!") def xcp_get_basic_information(args): send_arb_id = args.src rcv_arb_id = args.dst def callback_wrapper(callback): """ Adds handling of uninteresting or error messages to a callback function. :param callback: The callback function to run on successful messages :return: A callback function with extended message handling """ def c(msg): if msg.arbitration_id != rcv_arb_id: return if msg.data[0] == 0xfe: return if msg.data[0] == 0xff: callback(msg) else: print("Unexpected reply:\n{0}\n".format(msg)) return c class ProbeMessage: """Wrapper class for probe messages""" def __init__(self, message_data, callback): self.message_data = message_data self.callback = callback_wrapper(callback) def __str__(self): return "[{0}]".format(list_to_hex_str(self.message_data, ", ")) # Callback handler for GetId messages def print_msg_as_text(msg): print(list_to_hex_str(msg.data[1:], "")) def handle_get_id_reply(msg): can_wrap.send_single_message_with_callback([0xf5, msg.data[4]], callback_wrapper(print_msg_as_text)) # Define probe messages probe_msgs = [ProbeMessage([0xff], decode_connect_response), # Connect ProbeMessage([0xfb], decode_get_comm_mode_info_response), # GetCommMode ProbeMessage([0xfd], decode_get_status_response), # GetStatus ProbeMessage([0xfa, 0x00], handle_get_id_reply), # GetId ASCII text ProbeMessage([0xfa, 0x01], handle_get_id_reply), # GetId ASAM-MC2 filename w/o path/ext ProbeMessage([0xfa, 0x02], handle_get_id_reply), # GetId ASAM-MC2 filename with path/ext ProbeMessage([0xfa, 0x03], handle_get_id_reply), # GetId ASAM-MC2 URL ProbeMessage([0xfa, 0x04], handle_get_id_reply)] # GetId ASAM-MC2 fileToUpload # Initiate probing with CanActions(arb_id=send_arb_id) as can_wrap: print("Probing for XCP info") for probe in probe_msgs: print("Sending probe message: {0}".format(probe)) can_wrap.send_single_message_with_callback(probe.message_data, probe.callback) time.sleep(2) print("Probing finished") def xcp_memory_dump(args): """ Performs a memory dump to file or stdout via XCP. :param args: A namespace containing src, dst, start, length and f """ send_arb_id = args.src rcv_arb_id = args.dst start_address = args.start length = args.length dump_file = args.f # TODO Implement support for larger segments against ECUs which support this (e.g. 0xfc for test board) max_segment_size = 0x7 global byte_counter, bytes_left, dump_complete, segment_counter, timeout_start # Timeout timer dump_complete = False # Counters for data length byte_counter = 0 segment_counter = 0 def handle_upload_reply(msg): global byte_counter, bytes_left, dump_complete, timeout_start, segment_counter if msg.arbitration_id != rcv_arb_id: return if msg.data[0] == 0xfe: decode_xcp_error(msg) return if msg.data[0] == 0xff: # Reset timeout timer timeout_start = datetime.now() # Calculate end index of data to handle end_index = min(8, bytes_left + 1) if dump_file: with open(dump_file, "ab") as outfile: outfile.write(bytearray(msg.data[1:end_index])) else: print(list_to_hex_str(msg.data[1:end_index], " ")) # Update counters byte_counter += max_segment_size bytes_left -= max_segment_size if bytes_left < 1: if dump_file: print("\rDumping segment {0} ({1} b, 0 b left)".format(segment_counter, length), end="") print("Dump complete!") dump_complete = True elif byte_counter > max_segment_size - 1: # Dump another segment segment_counter += 1 if dump_file: # Print progress print("\rDumping segment {0} ({1} b, {2} b left)".format( segment_counter, ((segment_counter + 1) * max_segment_size + byte_counter), bytes_left), end="") stdout.flush() byte_counter = 0 can_wrap.send_single_message_with_callback([0xf5, min(max_segment_size, bytes_left)], handle_upload_reply) def handle_set_mta_reply(msg): if msg.arbitration_id != rcv_arb_id: return if msg.data[0] == 0xfe: decode_xcp_error(msg) return if msg.data[0] == 0xff: print("Set MTA acked") print("Dumping data:") # Initiate dumping if dump_file: print("\rDumping segment 0", end="") can_wrap.send_single_message_with_callback([0xf5, min(max_segment_size, bytes_left)], handle_upload_reply) else: print("Unexpected reply: {0}\n".format(msg)) def handle_connect_reply(msg): if msg.arbitration_id != rcv_arb_id: return if msg.data[0] == 0xfe: decode_xcp_error(msg) return if msg.data[0] == 0xff: print("Connected: Using", end=" ") # Check connect reply to see whether to reverse byte order for MTA msb_format = msg.data[2] & 1 if msb_format: print("Motorola format (MSB lower)") else: print("Intel format (LSB lower)") r.reverse() can_wrap.send_single_message_with_callback( [0xf6, 0x00, 0x00, 0x00, r[0], r[1], r[2], r[3]], handle_set_mta_reply) else: print("Unexpected connect reply: {0}\n".format(msg)) # Calculate address bytes (4 bytes, least significant first) r = [] n = start_address bytes_left = length # Calculate start address (r is automatically reversed after connect if needed) n &= 0xffffffff for i in range(4): r.append(n & 0xff) n >>= 8 # Make sure dump_file can be opened if specified (clearing it if it already exists) if dump_file: try: with open(dump_file, "w") as _: pass except IOError as e: print("Error when opening dump file:\n\n{0}".format(e)) return # Initialize with CanActions(arb_id=send_arb_id) as can_wrap: print("Attempting XCP memory dump") # Connect and prepare for dump can_wrap.send_single_message_with_callback([0xff, 0, 0, 0, 0, 0, 0, 0], handle_connect_reply) # Idle timeout handling timeout_start = datetime.now() while not dump_complete and datetime.now() - timeout_start < timedelta(seconds=3): pass if not dump_complete: print("\nERROR: Dump ended due to idle timeout") def parse_args(args): """ Parser for XCP module arguments. :return: Namespace containing action and action-specific arguments :rtype: argparse.Namespace """ parser = argparse.ArgumentParser(prog="cc.py xcp", formatter_class=argparse.RawDescriptionHelpFormatter, description="""XCP module for CaringCaribou""", epilog="""Example usage: cc.py xcp discovery cc.py xcp discovery -blacklist 0x100 0xabc cc.py xcp discovery -autoblacklist 10 cc.py xcp commands 0x3e8 0x3e9 cc.py xcp info 1000 1001 cc.py xcp dump 0x3e8 0x3e9 0x1fffb000 0x4800 -f bootloader.hex""") subparsers = parser.add_subparsers(dest="module_function") subparsers.required = True # Parser for XCP discovery parser_disc = subparsers.add_parser("discovery") parser_disc.add_argument("-min", type=parse_int_dec_or_hex, default=None) parser_disc.add_argument("-max", type=parse_int_dec_or_hex, default=None) parser_disc.add_argument("-blacklist", metavar="B", type=parse_int_dec_or_hex, default=[], nargs="+", help="arbitration IDs to ignore") parser_disc.add_argument("-autoblacklist", metavar="N", type=float, default=0, help="scan for interfering signals for N seconds and blacklist matching arbitration IDs") parser_disc.set_defaults(func=xcp_arbitration_id_discovery) # Parser for XCP commands discovery parser_comm = subparsers.add_parser("commands") parser_comm.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit from") parser_comm.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_comm.set_defaults(func=xcp_command_discovery) # Parser for XCP info parser_info = subparsers.add_parser("info") parser_info.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit from") parser_info.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_info.set_defaults(func=xcp_get_basic_information) # Parser for XCP data dump parser_dump = subparsers.add_parser("dump") parser_dump.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit from") parser_dump.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_dump.add_argument("start", type=parse_int_dec_or_hex, help="start address") # TODO: use length OR end address as mutually exclusive group? parser_dump.add_argument("length", type=parse_int_dec_or_hex, help="dump length") parser_dump.add_argument("-f", "-file", help="output file", default=None) parser_dump.set_defaults(func=xcp_memory_dump) args = parser.parse_args(args) return args def module_main(arg_list): """ Module main wrapper. :param arg_list: Module argument list """ try: args = parse_args(arg_list) args.func(args) except KeyboardInterrupt: print("\n\nTerminated by user")
22,119
39.438757
120
py
caringcaribou
caringcaribou-master/caringcaribou/modules/doip.py
from __future__ import print_function from caringcaribou.utils.common import list_to_hex_str, parse_int_dec_or_hex from caringcaribou.utils.constants import ARBITRATION_ID_MAX, ARBITRATION_ID_MAX_EXTENDED from caringcaribou.utils.constants import ARBITRATION_ID_MIN from caringcaribou.utils.iso14229_1 import Constants, NegativeResponseCodes from doipclient import DoIPClient from doipclient.connectors import DoIPClientUDSConnector from udsoncan.client import Client from udsoncan.services import * from sys import stdout, version_info import argparse import datetime import time import sys import struct # Handle large ranges efficiently in both python 2 and 3 if version_info[0] == 2: range = xrange UDS_SERVICE_NAMES = { 0x10: "DIAGNOSTIC_SESSION_CONTROL", 0x11: "ECU_RESET", 0x14: "CLEAR_DIAGNOSTIC_INFORMATION", 0x19: "READ_DTC_INFORMATION", 0x20: "RETURN_TO_NORMAL", 0x22: "READ_DATA_BY_IDENTIFIER", 0x23: "READ_MEMORY_BY_ADDRESS", 0x24: "READ_SCALING_DATA_BY_IDENTIFIER", 0x27: "SECURITY_ACCESS", 0x28: "COMMUNICATION_CONTROL", 0x2A: "READ_DATA_BY_PERIODIC_IDENTIFIER", 0x2C: "DYNAMICALLY_DEFINE_DATA_IDENTIFIER", 0x2D: "DEFINE_PID_BY_MEMORY_ADDRESS", 0x2E: "WRITE_DATA_BY_IDENTIFIER", 0x2F: "INPUT_OUTPUT_CONTROL_BY_IDENTIFIER", 0x31: "ROUTINE_CONTROL", 0x34: "REQUEST_DOWNLOAD", 0x35: "REQUEST_UPLOAD", 0x36: "TRANSFER_DATA", 0x37: "REQUEST_TRANSFER_EXIT", 0x38: "REQUEST_FILE_TRANSFER", 0x3D: "WRITE_MEMORY_BY_ADDRESS", 0x3E: "TESTER_PRESENT", 0x7F: "NEGATIVE_RESPONSE", 0x83: "ACCESS_TIMING_PARAMETER", 0x84: "SECURED_DATA_TRANSMISSION", 0x85: "CONTROL_DTC_SETTING", 0x86: "RESPONSE_ON_EVENT", 0x87: "LINK_CONTROL" } DELAY_DISCOVERY = 0.2 DELAY_TESTER_PRESENT = 0.5 DELAY_SECSEED_RESET = 0.01 DELAY_FUZZ_RESET = 3.901 TIMEOUT_SERVICES = 0.2 # Max number of arbitration IDs to backtrack during verification VERIFICATION_BACKTRACK = 5 # Extra time in seconds to wait for responses during verification VERIFICATION_EXTRA_DELAY = 0.5 BYTE_MIN = 0x00 BYTE_MAX = 0xFF DUMP_DID_MIN = 0x0000 DUMP_DID_MAX = 0xFFFF DUMP_DID_TIMEOUT = 0.2 # Diagnostic Message payload type - see Table 21 "Payload type diagnostic message structure" # https://python-doipclient.readthedocs.io/en/latest/messages.html PAYLOAD_TYPE = 0x8001 class DevNull: # Supress errors solution: # https://stackoverflow.com/questions/5925918/python-suppressing-errors-from-going-to-commandline def write(self, msg): pass # Duplicate testing from https://www.iditect.com/guide/python/python_howto_find_the_duplicates_in_a_list.html def find_duplicates(sequence): first_seen = set() first_seen_add = first_seen.add duplicates = set(i for i in sequence if i in first_seen or first_seen_add(i)) return duplicates def ecu_reset(client, reset_type): if reset_type == 1: client.ecu_reset(ECUReset.ResetType.hardReset) elif reset_type == 2: client.ecu_reset(ECUReset.ResetType.keyOffOnReset) elif reset_type == 3: client.ecu_reset(ECUReset.ResetType.softReset) elif reset_type == 4: client.ecu_reset(ECUReset.ResetType.enableRapidPowerShutDown) elif reset_type == 5: client.ecu_reset(ECUReset.ResetType.disableRapidPowerShutDown) def extended_session(client, session_type): if session_type == 1: client.change_session(DiagnosticSessionControl.Session.defaultSession) elif session_type == 2: client.change_session(DiagnosticSessionControl.Session.programmingSession) elif session_type == 3: client.change_session(DiagnosticSessionControl.Session.extendedDiagnosticSession) elif session_type == 4: client.change_session(DiagnosticSessionControl.Session.safetySystemDiagnosticSession) def uds_discovery(min_id, max_id, blacklist_args, auto_blacklist_duration, delay, print_results=True): """Scans for diagnostics support by brute forcing session control messages to different arbitration IDs. Returns a list of all (client_arb_id, server_arb_id) pairs found. :param min_id: start arbitration ID value :param max_id: end arbitration ID value :param blacklist_args: blacklist for arbitration ID values :param auto_blacklist_duration: seconds to scan for interfering arbitration IDs to blacklist automatically :param delay: delay between each message :param print_results: whether results should be printed to stdout :type min_id: int :type max_id: int :type blacklist_args: [int] :type auto_blacklist_duration: float :type delay: float :type print_results: bool :return: list of (client_arbitration_id, server_arbitration_id) pairs :rtype [(int, int)] """ # Set defaults if min_id is None: min_id = ARBITRATION_ID_MIN if max_id is None: if min_id <= ARBITRATION_ID_MAX: max_id = ARBITRATION_ID_MAX else: # If min_id is extended, use an extended default max_id as well max_id = ARBITRATION_ID_MAX_EXTENDED if auto_blacklist_duration is None: auto_blacklist_duration = 0 if blacklist_args is None: blacklist_args = [] # Sanity checks if max_id < min_id: raise ValueError("max_id must not be smaller than min_id - got min:0x{0:x}, max:0x{1:x}".format(min_id, max_id)) if auto_blacklist_duration < 0: raise ValueError("auto_blacklist_duration must not be smaller than 0, got {0}'".format(auto_blacklist_duration)) elif auto_blacklist_duration > 0: timeout = auto_blacklist_duration else: timeout = 2 blacklist = set(blacklist_args) found_arbitration_ids = [] send_arb_id = min_id - 1 print("Waiting for Vehicle Identification Announcement\n") print("Power cycle your ECU and wait for a few seconds for the broadcast to be received\n") address, announcement = DoIPClient.await_vehicle_announcement() logical_address = announcement.logical_address ip, port = address print("ECU IP and port found: ", ip, ",", port, "\nECU Logical Address Found: ", hex(logical_address), "\n") print("Searching for Client Node ID\n") client_id_status = 0 while send_arb_id < max_id: send_arb_id += 1 if print_results: print("\rSending Diagnostic Session Control to 0x{0:04x}" .format(send_arb_id), end="") try: if send_arb_id in blacklist: # Ignore blacklisted arbitration IDs continue if client_id_status == 0: doip_client = DoIPClient(ip, logical_address, client_logical_address=send_arb_id) else: doip_client = DoIPClient(ip, send_arb_id, client_logical_address=client_logical_address) conn = DoIPClientUDSConnector(doip_client) with Client(conn, request_timeout=timeout) as client: response = client.change_session(DiagnosticSessionControl.Session.defaultSession) if response.positive: print("\n\nFound diagnostics server " "listening at 0x{0:04x}, " "response at 0x{1:04x}" .format(logical_address, send_arb_id)) found_arb_id_pair = (logical_address, send_arb_id) found_arbitration_ids.append(found_arb_id_pair) if client_id_status == 0: client_id_status = 1 client_logical_address = send_arb_id send_arb_id = min_id - 1 print("\nSearching for Server Node ID\n") else: continue else: blacklist.add(send_arb_id) except KeyboardInterrupt: return found_arbitration_ids except ConnectionRefusedError: time.sleep(delay) except ConnectionResetError: time.sleep(delay) continue except TimeoutError: sys.stderr = DevNull() continue except OSError: print("Please check the connection and try again.\n") return found_arbitration_ids def __uds_discovery_wrapper(args): """Wrapper used to initiate a UDS discovery scan""" min_id = args.min max_id = args.max blacklist = args.blacklist auto_blacklist_duration = args.autoblacklist delay = args.delay print_results = True try: arb_id_pairs = uds_discovery(min_id, max_id, blacklist, auto_blacklist_duration, delay, print_results) if len(arb_id_pairs) == 0: # No UDS discovered print("\nDiagnostics service could not be found.") else: # Print result table print("\nIdentified diagnostics:\n") table_line = "+------------+------------+" print(table_line) print("| CLIENT ID | SERVER ID |") print(table_line) for (client_id, server_id) in arb_id_pairs: print("| 0x{0:08x} | 0x{1:08x} |" .format(client_id, server_id)) print(table_line) except ValueError as e: print("Discovery failed: {0}".format(e)) def service_discovery(arb_id_request, arb_id_response, timeout, min_id=BYTE_MIN, max_id=BYTE_MAX, print_results=True): """Scans for supported UDS services on the specified arbitration ID. Returns a list of found service IDs. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param timeout: delay between each request sent :param min_id: first service ID to scan :param max_id: last service ID to scan :param print_results: whether progress should be printed to stdout :type arb_id_request: int :type arb_id_response: int :type timeout: float :type min_id: int :type max_id: int :type print_results: bool :return: list of supported service IDs :rtype [int] """ found_services = [] print("Waiting for Vehicle Identification Announcement\n") print("Power cycle your ECU and wait for a few seconds for the broadcast to be received\n") address, announcement = DoIPClient.await_vehicle_announcement() logical_address = arb_id_request ip, port = address print("Discovering Services\n") try: for service_id in range(min_id, max_id + 1): if print_results: print("\rProbing service 0x{0:02x} ({0}/{1}): found {2}" .format(service_id, max_id, len(found_services)), end="") stdout.flush() doip_client = DoIPClient(ip, logical_address, client_logical_address=arb_id_response) conn = DoIPClientUDSConnector(doip_client) s = struct.pack("<h", service_id) doip_message = struct.pack("!HH", arb_id_response, arb_id_request) + s[:1] + b"\x00" try: with Client(conn, request_timeout=timeout) as client: extended_session(client, session_type=3) doip_client.send_doip(PAYLOAD_TYPE, doip_message) response = doip_client.receive_diagnostic(timeout) doip_client.close() if response is None or response[2] == NegativeResponseCodes.SERVICE_NOT_SUPPORTED: continue if response[2] == NegativeResponseCodes.SUB_FUNCTION_NOT_SUPPORTED or \ response[2] == NegativeResponseCodes.INCORRECT_MESSAGE_LENGTH_OR_INVALID_FORMAT: response_id = service_id response_service_id = response[2] status = response[2] if response_id != Constants.NR_SI: request_id = service_id found_services.append(request_id) elif status != NegativeResponseCodes.SERVICE_NOT_SUPPORTED: # Any other response than "service not supported" counts found_services.append(response_service_id) except ConfigError: sys.stderr = DevNull() time.sleep(3) continue except OSError: sys.stderr = DevNull() time.sleep(3) continue except IndexError: sys.stderr = DevNull() continue if print_results: print("\nDone!") except KeyboardInterrupt: if print_results: print("\nInterrupted by user!\n") return found_services except (ConnectionRefusedError, ConnectionResetError, TimeoutError, OSError): print("Please check the connection and try again.\n") return found_services def __service_discovery_wrapper(args): """Wrapper used to initiate a service discovery scan""" arb_id_request = args.src arb_id_response = args.dst timeout = args.timeout # Probe services found_services = service_discovery(arb_id_request, arb_id_response, timeout) # Print results for service_id in found_services: service_id_name = UDS_SERVICE_NAMES.get(service_id, "Unknown service") print("Supported service 0x{0:02x}: {1}".format(service_id, service_id_name)) def tester_present(arb_id_request, arb_id_response, delay, duration): """Sends TesterPresent messages to 'arb_id_request'. Stops automatically after 'duration' seconds or runs forever if this is None. :param arb_id_request: arbitration ID for requests :param delay: seconds between each request :param duration: seconds before automatically stopping, or None to continue forever :type arb_id_request: int :type delay: float :type duration: float or None """ # Calculate end timestamp if the TesterPresent should automatically # stop after a given duration auto_stop = duration is not None end_time = None if auto_stop: end_time = (datetime.datetime.now() + datetime.timedelta(seconds=duration)) print("\nWaiting for Vehicle Identification Announcement\n") print("Power cycle your ECU and wait for a few seconds for the broadcast to be received\n") address, announcement = DoIPClient.await_vehicle_announcement() logical_address = arb_id_request ip, port = address doip_client = DoIPClient(ip, logical_address, client_logical_address=arb_id_response) conn = DoIPClientUDSConnector(doip_client) with Client(conn, request_timeout=5) as client: counter = 1 print("Sending TesterPresent to arbitration ID {0} (0x{0:02x})" .format(arb_id_request)) print("\nPress Ctrl+C to stop\n") while True: client.tester_present() print("\rCounter:", counter, end="") stdout.flush() time.sleep(delay) counter += 1 if auto_stop and datetime.datetime.now() >= end_time: break def __tester_present_wrapper(args): """Wrapper used to initiate a TesterPresent session""" arb_id_request = args.src arb_id_response = args.dst delay = args.delay duration = args.duration tester_present(arb_id_request, arb_id_response, delay, duration) def __ecu_reset_wrapper(args): """Wrapper used to initiate ECU Reset""" logical_address = args.src reset_type = args.reset_type if not 1 <= reset_type <= 5: raise ValueError("reset type must be within interval 0x01-0x05") print("Sending ECU reset, type 0x{0:02x} to arbitration ID 0x{1:02x}".format(reset_type, logical_address)) try: print("\nWaiting for Vehicle Identification Announcement\n") print("Power cycle your ECU and wait for a few seconds for the broadcast to be received\n") address, announcement = DoIPClient.await_vehicle_announcement() ip, port = address doip_client = DoIPClient(ip, logical_address, client_logical_address=args.dst) conn = DoIPClientUDSConnector(doip_client) with Client(conn, request_timeout=5) as client: ecu_reset(client, reset_type) print(doip_client.request_entity_status()) except ConnectionRefusedError: print("Connection Refused: Please check the connection and try again.\n") except ConnectionResetError: print("Connection Reset: Please check the connection and try again.\n") except TimeoutError: print("Timeout Error: Please check the connection and try again.\n") except OSError: print("OSError: Please check the connection and try again.\n") def __security_seed_wrapper(args): """Wrapper used to initiate security seed dump""" arb_id_request = args.src arb_id_response = args.dst reset_type = args.reset session_type = args.sess_type level = args.sec_level num_seeds = args.num reset_delay = args.delay seed_list = [] print("\nWaiting for Vehicle Identification Announcement\n") print("Power cycle your ECU and wait for a few seconds for the broadcast to be received\n") address, announcement = DoIPClient.await_vehicle_announcement() logical_address = arb_id_request ip, port = address try: doip_client = DoIPClient(ip, logical_address, client_logical_address=arb_id_response) conn = DoIPClientUDSConnector(doip_client) print("Security seed dump started. Press Ctrl+C to stop.\n") with Client(conn) as client: while num_seeds > len(seed_list) or num_seeds == 0: # Diagnostics Session Control try: extended_session(client, session_type) except InvalidResponseException: print("Unable to enter extended session. Retrying...\n") continue try: # Request seed response = client.request_seed(level) if response is None: print("\nInvalid response") elif response.data: seed_list.append(response.data) print("Seed received: {}\t(Total captured: {})" .format(response.data, len(seed_list)), end="\r") stdout.flush() if reset_type: ecu_reset(client, reset_type) time.sleep(reset_delay) except NegativeResponseException: break except KeyboardInterrupt: print("Interrupted by user.") except ValueError as e: print(e) return except ConnectionRefusedError: print("Please check the connection and try again.\n") except ConnectionResetError: print("Please check the connection and try again.\n") except TimeoutError: print("Please check the connection and try again.\n") except OSError: print("Please check the connection and try again.\n") if len(seed_list) > 0: print("\n") print("Security Access Seeds captured:") for seed in seed_list: print("".join("{:02x}".format(x) for x in seed)) def __dump_dids_wrapper(args): """Wrapper used to initiate data identifier dump""" arb_id_request = args.src arb_id_response = args.dst timeout = args.timeout min_did = args.min_did max_did = args.max_did print_results = True dump_dids(arb_id_request, arb_id_response, timeout, min_did, max_did, print_results) def dump_dids(arb_id_request, arb_id_response, timeout, min_did=DUMP_DID_MIN, max_did=DUMP_DID_MAX, print_results=True): """ Sends read data by identifier (DID) messages to 'arb_id_request'. Returns a list of positive responses received from 'arb_id_response' within 'timeout' seconds or an empty list if no positive responses were received. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param timeout: seconds to wait for response before timeout, or None for default UDS timeout :param min_did: minimum device identifier to read :param max_did: maximum device identifier to read :param print_results: whether progress should be printed to stdout :type arb_id_request: int :type arb_id_response: int :type timeout: float or None :type min_did: int :type max_did: int :type print_results: bool :return: list of tuples containing DID and response bytes on success, empty list if no responses :rtype [(int, [int])] or [] """ # Sanity checks if isinstance(timeout, float) and timeout < 0.0: raise ValueError("Timeout value ({0}) cannot be negative" .format(timeout)) if max_did < min_did: raise ValueError("max_did must not be smaller than min_did - got min:0x{0:x}, max:0x{1:x}".format( min_did, max_did)) responses = [] print("Waiting for Vehicle Identification Announcement\n") print("Power cycle your ECU and wait for a few seconds for the broadcast to be received\n") address, announcement = DoIPClient.await_vehicle_announcement() logical_address = arb_id_request ip, port = address print("Discovering DIDs\n") try: doip_client = DoIPClient(ip, logical_address, client_logical_address=arb_id_response) conn = DoIPClientUDSConnector(doip_client) if print_results: print("Dumping DIDs in range 0x{:04x}-0x{:04x}\n".format(min_did, max_did)) print("Identified DIDs:") print("DID Value (hex)") for identifier in range(min_did, max_did + 1): try: with Client(conn, request_timeout=timeout) as client: extended_session(client, session_type=3) response = client.read_data_by_identifier(identifier) if response.positive: responses.append((identifier, response.data)) if print_results: print("0x{:04x}".format(identifier), list_to_hex_str(response)) except ConfigError: sys.stderr = DevNull() continue if print_results: print("\nDone!") return responses except ConnectionRefusedError: print("Please check the connection and try again.\n") except ConnectionResetError: print("Please check the connection and try again.\n") except TimeoutError: print("Please check the connection and try again.\n") except OSError: print("Please check the connection and try again.\n") def seed_randomness_fuzzer(args): """Wrapper used to initiate security randomness fuzzer""" arb_id_request = args.src arb_id_response = args.dst session_type = args.sess_type security_level = args.sec_level iterations = args.iter reset_delay = args.delay reset_type = args.reset_method inter = args.inter_delay seed_list = [] print("Waiting for Vehicle Identification Announcement\n") print("Power cycle your ECU and wait for a few seconds for the broadcast to be received\n") address, announcement = DoIPClient.await_vehicle_announcement() logical_address = arb_id_request ip, port = address try: # Issue first reset with the supplied delay time print("Security seed dump started. Press Ctrl+C if you need to stop.\n") for _ in range(iterations): try: with DoIPClient(ip, logical_address, client_logical_address=arb_id_response) as doip_client: conn = DoIPClientUDSConnector(doip_client) with Client(conn) as client: extended_session(client, session_type) time.sleep(inter) seed_response = client.request_seed(security_level) seed_hex_str = list_to_hex_str(seed_response).data seed_list.append(seed_hex_str) print("Seed received: {0}".format(seed_hex_str)) ecu_reset(client, reset_type) time.sleep(reset_delay) except TimeoutError: print("Timeout Error Exception: You may need to increase the intermediate delay (-id).") time.sleep(0.5) continue except NegativeResponseException: time.sleep(0.5) continue except ConnectionRefusedError: print("Connection Refused Error: You may need to increase the reset delay (-d).") time.sleep(0.5) continue except KeyboardInterrupt: print("Interrupted by user.") except ValueError as e: print(e) return # Print captured seeds and found duplicates if len(seed_list) > 0: print("\n") print("Security Access Seeds captured:") for seed in seed_list: print(seed) print("\nDuplicates found: \n", find_duplicates(seed_list)) def __parse_args(args): """Parser for module arguments""" parser = argparse.ArgumentParser( prog="cc.py doip", formatter_class=argparse.RawDescriptionHelpFormatter, description="DoIP module for " "CaringCaribou", epilog="""Example usage: cc.py doip discovery cc.py doip discovery -blacklist 0x123 0x456 cc.py doip discovery -autoblacklist 10 cc.py doip services 0x733 0x633 cc.py doip ecu_reset 1 0x733 0x633 cc.py doip testerpresent 0x733 cc.py doip security_seed 0x3 0x1 0x733 0x633 -r 1 -d 0.5 cc.py doip dump_dids 0x733 0x633 cc.py doip dump_dids 0x733 0x633 --min_did 0x6300 --max_did 0x6fff -t 0.1 cc.py doip seed_randomness_fuzzer 2 2 0x733 0x633 -m 1 -t 10 -d 50 -id 4""") subparsers = parser.add_subparsers(dest="module_function") subparsers.required = True # Parser for diagnostics discovery parser_discovery = subparsers.add_parser("discovery") parser_discovery.add_argument("-min", type=parse_int_dec_or_hex, default=None, help="min arbitration ID " "to send request for") parser_discovery.add_argument("-max", type=parse_int_dec_or_hex, default=None, help="max arbitration ID " "to send request for") parser_discovery.add_argument("-b", "--blacklist", metavar="B", type=parse_int_dec_or_hex, default=[], nargs="+", help="arbitration IDs to blacklist " "responses from") parser_discovery.add_argument("-ab", "--autoblacklist", metavar="N", type=float, default=0, help="listen for false positives for N seconds " "and blacklist matching arbitration " "IDs before running discovery") parser_discovery.add_argument("-d", "--delay", metavar="D", type=float, default=DELAY_DISCOVERY, help="D seconds delay between messages " "(default: {0})".format(DELAY_DISCOVERY)) parser_discovery.set_defaults(func=__uds_discovery_wrapper) # Parser for diagnostics service discovery parser_info = subparsers.add_parser("services") parser_info.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_info.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_info.add_argument("-t", "--timeout", metavar="T", type=float, default=TIMEOUT_SERVICES, help="wait T seconds for response before " "timeout (default: {0})" .format(TIMEOUT_SERVICES)) parser_info.set_defaults(func=__service_discovery_wrapper) # Parser for ECU Reset parser_ecu_reset = subparsers.add_parser("ecu_reset") parser_ecu_reset.add_argument("reset_type", metavar="type", type=parse_int_dec_or_hex, help="Reset type: 1=hard, 2=key off/on, " "3=soft, " "4=enable rapid power shutdown, " "5=disable rapid power shutdown") parser_ecu_reset.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_ecu_reset.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_ecu_reset.set_defaults(func=__ecu_reset_wrapper) # Parser for TesterPresent parser_tp = subparsers.add_parser("testerpresent") parser_tp.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_tp.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_tp.add_argument("-d", "--delay", metavar="D", type=float, default=DELAY_TESTER_PRESENT, help="send TesterPresent every D seconds " "(default: {0})".format(DELAY_TESTER_PRESENT)) parser_tp.add_argument("-dur", "--duration", metavar="S", type=float, help="automatically stop after S seconds") parser_tp.set_defaults(func=__tester_present_wrapper) # Parser for SecuritySeedDump parser_secseed = subparsers.add_parser("security_seed") parser_secseed.add_argument("sess_type", metavar="stype", type=parse_int_dec_or_hex, help="Session Type: 1=defaultSession " "2=programmingSession 3=extendedSession " "4=safetySession ") parser_secseed.add_argument("sec_level", metavar="level", type=parse_int_dec_or_hex, help="Security level: " "[0x1-0x41 (odd only)]=OEM " "0x5F=EOLPyrotechnics " "[0x61-0x7E]=Supplier " "[0x0, 0x43-0x5E, 0x7F]=ISOSAEReserved") parser_secseed.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_secseed.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_secseed.add_argument("-r", "--reset", metavar="RTYPE", type=parse_int_dec_or_hex, help="Enable reset between security seed " "requests. Valid RTYPE integers are: " "1=hardReset, 2=key off/on, 3=softReset, " "4=enable rapid power shutdown, " "5=disable rapid power shutdown. " "(default: None)") parser_secseed.add_argument("-d", "--delay", metavar="D", type=float, default=DELAY_SECSEED_RESET, help="Wait D seconds between reset and " "security seed request. You'll likely " "need to increase this when using RTYPE: " "1=hardReset. Does nothing if RTYPE " "is None. (default: {0})" .format(DELAY_SECSEED_RESET)) parser_secseed.add_argument("-n", "--num", metavar="NUM", default=0, type=parse_int_dec_or_hex, help="Specify a positive number of security" " seeds to capture before terminating. " "A '0' is interpreted as infinity. " "(default: 0)") parser_secseed.set_defaults(func=__security_seed_wrapper) # Parser for dump_did parser_did = subparsers.add_parser("dump_dids") parser_did.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_did.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_did.add_argument("-t", "--timeout", type=float, metavar="T", default=DUMP_DID_TIMEOUT, help="wait T seconds for response before " "timeout") parser_did.add_argument("--min_did", type=parse_int_dec_or_hex, default=DUMP_DID_MIN, help="minimum device identifier (DID) to read (default: 0x0000)") parser_did.add_argument("--max_did", type=parse_int_dec_or_hex, default=DUMP_DID_MAX, help="maximum device identifier (DID) to read (default: 0xFFFF)") parser_did.set_defaults(func=__dump_dids_wrapper) # Parser for Delay fuzz testing parser_randomness_fuzzer = subparsers.add_parser("seed_randomness_fuzzer") parser_randomness_fuzzer.add_argument("sess_type", metavar="stype", type=parse_int_dec_or_hex, help="Session Type: 1=defaultSession " "2=programmingSession 3=extendedSession " "4=safetySession ") parser_randomness_fuzzer.add_argument("sec_level", metavar="level", type=parse_int_dec_or_hex, help="Security level: " "[0x1-0x41 (odd only)]=OEM " "0x5F=EOLPyrotechnics " "[0x61-0x7E]=Supplier " "[0x0, 0x43-0x5E, 0x7F]=ISOSAEReserved") parser_randomness_fuzzer.add_argument("src", type=parse_int_dec_or_hex, help="arbitration ID to transmit to") parser_randomness_fuzzer.add_argument("dst", type=parse_int_dec_or_hex, help="arbitration ID to listen to") parser_randomness_fuzzer.add_argument("-t", "--iter", metavar="ITERATIONS", default=1000, type=parse_int_dec_or_hex, help="Number of iterations of seed requests. " "It is highly suggested to perform >=1000 " "for accurate results. " "(default: 1000)") parser_randomness_fuzzer.add_argument("-r", "--reset", metavar="RTYPE", default=1, type=parse_int_dec_or_hex, help="Enable reset between security seed " "requests. Valid RTYPE integers are: " "1=hardReset, 2=key off/on, 3=softReset, " "4=enable rapid power shutdown, " "5=disable rapid power shutdown. " "This attack is based on hard ECUReset (1) " "as it targets seed randomness based on " "the system clock. (default: hardReset)") parser_randomness_fuzzer.add_argument("-id", "--inter_delay", metavar="RTYPE", default=0.1, type=float, help="Intermediate delay between messages:" "(default: 0.1)") parser_randomness_fuzzer.add_argument("-m", "--reset_method", metavar="RMETHOD", default=1, type=parse_int_dec_or_hex, help="The method that the ECUReset will happen: " "1=before each seed request " "0=once before the seed requests start " "(default: 1) *This method works better with option 1.*") parser_randomness_fuzzer.add_argument("-d", "--delay", metavar="D", type=float, default=DELAY_SECSEED_RESET, help="Wait D seconds between reset and " "security seed request. You'll likely " "need to increase this when using RTYPE: " "1=hardReset. Does nothing if RTYPE " "is None. (default: {0})" .format(DELAY_FUZZ_RESET)) parser_randomness_fuzzer.set_defaults(func=seed_randomness_fuzzer) args = parser.parse_args(args) return args def module_main(arg_list): """Module main wrapper""" try: args = __parse_args(arg_list) args.func(args) except KeyboardInterrupt: print("\n\nTerminated by user")
39,207
40.93369
120
py
caringcaribou
caringcaribou-master/caringcaribou/tests/test_module_uds.py
from __future__ import print_function from caringcaribou.utils.iso14229_1 import Constants, Iso14229_1, NegativeResponseCodes, ServiceID, Services from caringcaribou.tests.mock.mock_ecu_uds import MockEcuIso14229 from caringcaribou.modules import uds import unittest class UdsModuleTestCase(unittest.TestCase): ARB_ID_REQUEST = 0x300E ARB_ID_RESPONSE = 0x300F # Timeout (in seconds) when waiting for response during bruteforce BRUTEFORCE_TIMEOUT = 0.01 def setUp(self): # Initialize mock ECU self.ecu = MockEcuIso14229(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE) # Remove response delay self.ecu.DELAY_BEFORE_RESPONSE = 0.0 self.ecu.start_server() def tearDown(self): if isinstance(self.ecu, MockEcuIso14229): self.ecu.__exit__(None, None, None) def test_uds_discovery(self): # Discovery arguments start_arb_id = self.ARB_ID_REQUEST - 5 end_arb_id = self.ARB_ID_REQUEST + 5 blacklist = [] auto_blacklist_duration = 0 timeout = self.BRUTEFORCE_TIMEOUT verify = True print_results = False # Perform UDS discovery result = uds.uds_discovery(min_id=start_arb_id, max_id=end_arb_id, blacklist_args=blacklist, auto_blacklist_duration=auto_blacklist_duration, delay=timeout, verify=verify, print_results=print_results) expected_result = [(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE)] self.assertListEqual(result, expected_result, "UDS discovery gave '{0}', expected '{1}'".format( result, expected_result)) def test_uds_discovery_blacklist(self): # Discovery arguments start_arb_id = self.ARB_ID_REQUEST - 5 end_arb_id = self.ARB_ID_REQUEST + 5 # Blacklist the arbitration ID used for response blacklist = [self.ARB_ID_RESPONSE] auto_blacklist_duration = 0 timeout = self.BRUTEFORCE_TIMEOUT verify = True print_results = False # Perform UDS discovery result = uds.uds_discovery(min_id=start_arb_id, max_id=end_arb_id, blacklist_args=blacklist, auto_blacklist_duration=auto_blacklist_duration, delay=timeout, verify=verify, print_results=print_results) # No results expected due to blacklist expected_result = [] self.assertListEqual(result, expected_result, "UDS discovery gave '{0}', expected '{1}'".format( result, expected_result)) def test_service_discovery(self): # Service discovery arguments range_start = 0x09 range_end = 0x13 print_results = False # Perform service discovery result = uds.service_discovery(arb_id_request=self.ARB_ID_REQUEST, arb_id_response=self.ARB_ID_RESPONSE, timeout=self.BRUTEFORCE_TIMEOUT, min_id=range_start, max_id=range_end, print_results=print_results) # Supported services within specified range expected_result = [ServiceID.DIAGNOSTIC_SESSION_CONTROL, ServiceID.ECU_RESET] self.assertListEqual(result, expected_result, "UDS service discovery gave '{0}', expected '{1}'".format( result, expected_result)) def test_service_discovery_empty_range(self): # Service discovery arguments range_start = 0x00 range_end = 0x05 print_results = False # Perform service discovery result = uds.service_discovery(arb_id_request=self.ARB_ID_REQUEST, arb_id_response=self.ARB_ID_RESPONSE, timeout=self.BRUTEFORCE_TIMEOUT, min_id=range_start, max_id=range_end, print_results=print_results) # No services should be found within range expected_result = [] self.assertListEqual(result, expected_result, "UDS service discovery gave '{0}', expected no hits".format( result)) def test_ecu_reset_hard_reset_success(self): # ECU Reset arguments reset_type = Services.EcuReset.ResetType.HARD_RESET timeout = None # Perform ECU Reset result = uds.ecu_reset(arb_id_request=self.ARB_ID_REQUEST, arb_id_response=self.ARB_ID_RESPONSE, reset_type=reset_type, timeout=timeout) # Expected response format for successful request expected_response_id = Iso14229_1.get_service_response_id(Services.EcuReset.service_id) expected_result = [expected_response_id, reset_type] self.assertListEqual(result, expected_result, "ECU Reset gave '{0}', expected '{1}'".format( result, expected_result)) def test_ecu_reset_unsupported_reset_type_failure(self): # Invalid reset type reset_type = 0x00 timeout = None # Perform ECU Reset result = uds.ecu_reset(arb_id_request=self.ARB_ID_REQUEST, arb_id_response=self.ARB_ID_RESPONSE, reset_type=reset_type, timeout=timeout) # Expected response format for invalid request expected_response_id = Services.EcuReset.service_id expected_nrc = NegativeResponseCodes.SUB_FUNCTION_NOT_SUPPORTED expected_result = [Constants.NR_SI, expected_response_id, expected_nrc] self.assertListEqual(result, expected_result, "ECU Reset gave '{0}', expected '{1}'".format( result, expected_result)) def test_security_access_request_seed_send_key_success(self): level_seed = 0x01 data_record = [] timeout = None expected_response_id = Iso14229_1.get_service_response_id(Services.SecurityAccess.service_id) # Request seed seed_result = uds.request_seed(arb_id_request=self.ARB_ID_REQUEST, arb_id_response=self.ARB_ID_RESPONSE, level=level_seed, data_record=data_record, timeout=timeout) expected_seed = self.ecu.SECURITY_ACCESS_SEED expected_seed_result = [expected_response_id, level_seed] + expected_seed self.assertListEqual(seed_result, expected_seed_result, "Security Access: Request seed gave '{0}', expected '{1}'".format( seed_result, expected_seed_result)) # Send key level_key = uds.Services.SecurityAccess.RequestSeedOrSendKey().get_send_key_for_request_seed(level_seed) key = self.ecu.SECURITY_ACCESS_KEY key_result = uds.send_key(arb_id_request=self.ARB_ID_REQUEST, arb_id_response=self.ARB_ID_RESPONSE, level=level_key, key=key, timeout=timeout) expected_key_result = [expected_response_id, level_key] self.assertListEqual(key_result, expected_key_result, "Security Access: Send key gave '{0}', expected '{1}'".format( key_result, expected_key_result)) def test_security_access_request_seed_invalid_level(self): # Level 0x00 lies outside of allowed interval level = 0x00 data_record = [] timeout = None with self.assertRaises(ValueError): uds.request_seed(arb_id_request=self.ARB_ID_REQUEST, arb_id_response=self.ARB_ID_RESPONSE, level=level, data_record=data_record, timeout=timeout) def test_dump_dids(self): # mock ECU responds to DIDs 0x0001, 0x0101, 0x0201...0xff01 # response data is always 6272 # scanning 0x0000...0x0101 should yield 2 positive responses out of 258 requests # and each response will contain 6272 # timeout = None min_did = 0x0000 max_did = 0x0101 print_results = False expected_response_cnt = 2 expected_response = [0x62, 0x72] responses = uds.dump_dids(arb_id_request=self.ARB_ID_REQUEST, arb_id_response=self.ARB_ID_RESPONSE, timeout=timeout, min_did=min_did, max_did=max_did, print_results=print_results) # first check there are proper number of responses self.assertEqual(expected_response_cnt, len(responses)) # next check the responses contain the proper data for response in responses: self.assertListEqual(expected_response, response[1])
9,568
46.137931
114
py
caringcaribou
caringcaribou-master/caringcaribou/tests/test_iso_14229_1.py
from __future__ import print_function from caringcaribou.utils.can_actions import DEFAULT_INTERFACE from caringcaribou.tests.mock.mock_ecu_uds import MockEcuIso14229 from caringcaribou.utils import iso14229_1 from caringcaribou.utils import iso15765_2 import can import unittest class DiagnosticsOverIsoTpTestCase(unittest.TestCase): ARB_ID_REQUEST = 0x200C ARB_ID_RESPONSE = 0x200D def setUp(self): # Initialize mock ECU self.ecu = MockEcuIso14229(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE) self.ecu.start_server() # Initialize virtual CAN bus can_bus = can.Bus(DEFAULT_INTERFACE) # Setup diagnostics on top of ISO-TP layer self.tp = iso15765_2.IsoTp(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE, bus=can_bus) self.diagnostics = iso14229_1.Iso14229_1(self.tp) # Reduce timeout value to speed up testing self.diagnostics.P3_CLIENT = 0.5 def tearDown(self): if isinstance(self.ecu, MockEcuIso14229): self.ecu.__exit__(None, None, None) if isinstance(self.diagnostics, iso14229_1.Iso14229_1): self.diagnostics.__exit__(None, None, None) if isinstance(self.tp, iso15765_2.IsoTp): self.tp.__exit__(None, None, None) def verify_positive_response(self, service_id, response, expected_data): """ Verifies that 'response' is a valid positive response for 'service_id' with a payload matching 'expected_data' :param service_id: Service ID (SIDRQ) of the request :param response: Response data :param expected_data: Expected data payload in 'response' :return: None """ self.assertIsInstance(response, list, "No response was received") self.assertGreater(len(response), 1, "Expected positive response length >1, got {0}".format(response)) response_sid = response[0] response_data = response[1:] expected_response_sid = self.diagnostics.get_service_response_id(service_id) self.assertEqual(response_sid, expected_response_sid, "Response SID (SIDPR) '{0}' does not match expected " "value '{1}'".format(hex(response_sid), hex(expected_response_sid))) self.assertTrue(self.diagnostics.is_positive_response(response)) self.assertListEqual(response_data, expected_data) def verify_negative_response(self, service_id, response, expected_nrc): """ Verifies that 'response' is a valid negative response for 'service_id' matching 'expected_nrc' :param service_id: Service ID (SIDRQ) of the request :param response: Response data :param expected_nrc: Expected negative response code (NRC) :return: None """ self.assertIsInstance(response, list, "No response was received") self.assertEqual(len(response), 3, "Negative response should have length '3', got {0}".format(response)) request_sid = response[1] self.assertEqual(request_sid, service_id, "Request SID (SIDRQ) of response does not match expected value") self.assertFalse(self.diagnostics.is_positive_response(response)) response_nrc = response[2] self.assertEqual(response_nrc, expected_nrc, "NRC of response does not match expected value") def test_create_iso_14229_1(self): self.assertIsInstance(self.diagnostics, iso14229_1.Iso14229_1, "Failed to initialize ISO-14229-1") def test_read_data_by_identifier_success(self): service_id = iso14229_1.ServiceID.READ_DATA_BY_IDENTIFIER identifier = [MockEcuIso14229.IDENTIFIER_REQUEST_POSITIVE] expected_response = [MockEcuIso14229.IDENTIFIER_REQUEST_POSITIVE_RESPONSE] result = self.diagnostics.read_data_by_identifier(identifier=identifier) self.verify_positive_response(service_id, result, expected_response) def test_read_data_by_identifier_failure(self): service_id = iso14229_1.ServiceID.READ_DATA_BY_IDENTIFIER identifier = [MockEcuIso14229.IDENTIFIER_REQUEST_NEGATIVE] expected_nrc = iso14229_1.NegativeResponseCodes.CONDITIONS_NOT_CORRECT result = self.diagnostics.read_data_by_identifier(identifier=identifier) self.verify_negative_response(service_id, result, expected_nrc) def test_write_data_by_identifier_success(self): service_id = iso14229_1.ServiceID.WRITE_DATA_BY_IDENTIFIER request_identifier = MockEcuIso14229.REQUEST_IDENTIFIER_VALID request_data = MockEcuIso14229.REQUEST_VALUE expected_response = [(request_identifier >> 8) & 0xFF, request_identifier & 0xFF] result = self.diagnostics.write_data_by_identifier(identifier=request_identifier, data=request_data) self.verify_positive_response(service_id, result, expected_response) def test_write_data_by_identifier_failure(self): service_id = iso14229_1.ServiceID.WRITE_DATA_BY_IDENTIFIER request_identifier = MockEcuIso14229.REQUEST_IDENTIFIER_INVALID request_data = MockEcuIso14229.REQUEST_VALUE expected_nrc = iso14229_1.NegativeResponseCodes.CONDITIONS_NOT_CORRECT result = self.diagnostics.write_data_by_identifier(identifier=request_identifier, data=request_data) self.verify_negative_response(service_id, result, expected_nrc) def test_read_memory_by_address_success(self): service_id = iso14229_1.ServiceID.READ_MEMORY_BY_ADDRESS length_and_format = MockEcuIso14229.REQUEST_ADDRESS_LENGTH_AND_FORMAT start_address = MockEcuIso14229.REQUEST_ADDRESS request_data_size = MockEcuIso14229.REQUEST_DATA_SIZE end_address = start_address + request_data_size result = self.diagnostics.read_memory_by_address(address_and_length_format=length_and_format, memory_address=start_address, memory_size=request_data_size) expected_response = MockEcuIso14229.DATA[start_address:end_address] self.verify_positive_response(service_id, result, expected_response) def test_read_memory_by_address_failure_on_invalid_length(self): service_id = iso14229_1.ServiceID.READ_MEMORY_BY_ADDRESS expected_nrc = iso14229_1.NegativeResponseCodes.REQUEST_OUT_OF_RANGE length_and_format = MockEcuIso14229.REQUEST_ADDRESS_LENGTH_AND_FORMAT start_address = 0 # Request memory outside of the available address space, which should result in a failure request_data_size = len(MockEcuIso14229.DATA) + 1 result = self.diagnostics.read_memory_by_address(address_and_length_format=length_and_format, memory_address=start_address, memory_size=request_data_size) self.verify_negative_response(service_id, result, expected_nrc) def test_ecu_reset_success(self): service_id = iso14229_1.ServiceID.ECU_RESET reset_type = iso14229_1.Services.EcuReset.ResetType.HARD_RESET expected_response = [reset_type] result = self.diagnostics.ecu_reset(reset_type=reset_type) self.verify_positive_response(service_id, result, expected_response) def test_ecu_reset_failure_on_invalid_reset_type(self): service_id = iso14229_1.ServiceID.ECU_RESET expected_nrc = iso14229_1.NegativeResponseCodes.SUB_FUNCTION_NOT_SUPPORTED # This reset type is ISO SAE Reserved and thus an invalid value reset_type = 0x00 result = self.diagnostics.ecu_reset(reset_type=reset_type) self.verify_negative_response(service_id, result, expected_nrc) def test_ecu_reset_success_suppress_positive_response(self): reset_type = iso14229_1.Services.EcuReset.ResetType.SOFT_RESET # Suppress positive response reset_type |= 0x80 result = self.diagnostics.ecu_reset(reset_type=reset_type) self.assertIsNone(result) def test_ecu_reset_failure_suppress_positive_response(self): service_id = iso14229_1.ServiceID.ECU_RESET expected_nrc = iso14229_1.NegativeResponseCodes.SUB_FUNCTION_NOT_SUPPORTED # ISO SAE Reserved reset type 0x00, with suppress positive response bit set reset_type = 0x80 result = self.diagnostics.ecu_reset(reset_type=reset_type) self.verify_negative_response(service_id, result, expected_nrc)
8,713
53.4625
118
py
caringcaribou
caringcaribou-master/caringcaribou/tests/test_iso_15765_2.py
from __future__ import print_function from caringcaribou.tests.mock.mock_ecu_iso_tp import MockEcuIsoTp from caringcaribou.utils import iso15765_2 from caringcaribou.utils.can_actions import DEFAULT_INTERFACE import can import unittest class IsoTpTestCase(unittest.TestCase): ARB_ID_REQUEST = 0x100A ARB_ID_RESPONSE = 0x100B def setUp(self): # Initialize mock ECU self.ecu = MockEcuIsoTp(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE) self.ecu.start_server() # Initialize virtual CAN bus can_bus = can.Bus(DEFAULT_INTERFACE) # Setup ISO-TP layer self.tp = iso15765_2.IsoTp(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE, bus=can_bus) def tearDown(self): if isinstance(self.ecu, MockEcuIsoTp): self.ecu.__exit__(None, None, None) if isinstance(self.tp, iso15765_2.IsoTp): self.tp.__exit__(None, None, None) def test_create_iso_15765_2(self): self.assertIsInstance(self.tp, iso15765_2.IsoTp, "Failed to initialize ISO-TP") def test_single_frame(self): # Send request self.tp.send_request(MockEcuIsoTp.MOCK_SINGLE_FRAME_REQUEST) # Receive response response = self.tp.indication() # Validate response self.assertIsInstance(response, list, "No SF response received") self.assertEqual(response, MockEcuIsoTp.MOCK_SINGLE_FRAME_RESPONSE) def test_multi_frame_two_frames(self): # Send request self.tp.send_request(MockEcuIsoTp.MOCK_MULTI_FRAME_TWO_MESSAGES_REQUEST) # Receive response response = self.tp.indication() # Validate response self.assertIsInstance(response, list, "No multi-frame response received") self.assertEqual(response, MockEcuIsoTp.MOCK_MULTI_FRAME_TWO_MESSAGES_RESPONSE) def test_multi_frame_long_message(self): # Send request self.tp.send_request(MockEcuIsoTp.MOCK_MULTI_FRAME_LONG_MESSAGE_REQUEST) # Receive response response = self.tp.indication() # Validate response self.assertIsInstance(response, list, "No multi-frame response received") self.assertEqual(response, MockEcuIsoTp.MOCK_MULTI_FRAME_LONG_MESSAGE_RESPONSE) def test_fail_too_long_message(self): with self.assertRaises(ValueError): max_allowed_length = iso15765_2.IsoTp.MAX_MESSAGE_LENGTH too_long_message = [0x0] * (max_allowed_length + 1) self.tp.send_request(too_long_message)
2,511
38.25
90
py
caringcaribou
caringcaribou-master/caringcaribou/tests/__init__.py
import os def load_tests(loader, standard_tests, pattern): this_dir = os.path.dirname(__file__) package_tests = loader.discover(start_dir=this_dir, pattern='test_*') standard_tests.addTests(package_tests) return standard_tests
244
29.625
73
py
caringcaribou
caringcaribou-master/caringcaribou/tests/test_send.py
from caringcaribou.modules import send import unittest class SendFileParserTestCase(unittest.TestCase): RESULT_DATA_C0FFEE = [0xc0, 0xff, 0xee] RESULT_DATA_DEAD_CAFE = [0xde, 0xad, 0xca, 0xfe] def test_parse_candump_line(self): line = "(1499197954.029156) can0 123#c0ffee" message, timestamp = send.parse_candump_line(line, None, None) self.assertListEqual(message.data, self.RESULT_DATA_C0FFEE) def test_parse_pythoncan_line_v_20(self): # Parse message format for python-can 2.0 line = "Timestamp: 0.000000 ID: 017a 000 DLC: 3 c0 ff ee" message, timestamp = send.parse_pythoncan_line(line, None, None) self.assertListEqual(message.data, self.RESULT_DATA_C0FFEE) def test_parse_pythoncan_line_v_21(self): # Parse message format for python-can 2.1 line = "Timestamp: 0.000000 ID: 0000 S DLC: 3 c0 ff ee" message, timestamp = send.parse_pythoncan_line(line, None, None) self.assertListEqual(message.data, self.RESULT_DATA_C0FFEE) def test_parse_pythoncan_line_v_21_flags(self): # Parse message format for python-can 2.1 with flags line = "Timestamp: 0.000000 ID: 00000000 X E R DLC: 4 de ad ca fe" message, timestamp = send.parse_pythoncan_line(line, None, None) self.assertListEqual(message.data, self.RESULT_DATA_DEAD_CAFE) def test_parse_pythoncan_line_v_30_channel(self): # Parse message format for python-can 3.0 with channel line = "Timestamp: 0.000000 ID: 00000000 X DLC: 3 c0 ff ee " \ " Channel: vcan0" message, timestamp = send.parse_pythoncan_line(line, None, None) self.assertListEqual(message.data, self.RESULT_DATA_C0FFEE) def test_parse_pythoncan_line_v_30_flags(self): # Parse message format for python-can 3.0 with flags line = "Timestamp: 0.000000 ID: 00000000 X R DLC: 4 de ad ca fe" message, timestamp = send.parse_pythoncan_line(line, None, None) self.assertListEqual(message.data, self.RESULT_DATA_DEAD_CAFE)
2,222
48.4
102
py
caringcaribou
caringcaribou-master/caringcaribou/tests/mock/mock_ecu_iso_tp.py
import multiprocessing import time from caringcaribou.utils.iso15765_2 import IsoTp from caringcaribou.tests.mock.mock_ecu import MockEcu class MockEcuIsoTp(MockEcu): """ISO-15765-2 (ISO-TP) mock ECU handler""" MOCK_SINGLE_FRAME_REQUEST = [0x01, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF] MOCK_SINGLE_FRAME_RESPONSE = list(range(0, 0x07)) MOCK_MULTI_FRAME_TWO_MESSAGES_REQUEST = [0xC0, 0xFF, 0xEE, 0x00, 0x02, 0x00, 0x00] MOCK_MULTI_FRAME_TWO_MESSAGES_RESPONSE = list(range(0, 0x0D)) MOCK_MULTI_FRAME_LONG_MESSAGE_REQUEST = [0x02, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F] MOCK_MULTI_FRAME_LONG_MESSAGE_RESPONSE = list(range(0, 34)) def __init__(self, arb_id_request, arb_id_response, bus=None): MockEcu.__init__(self, bus) self.ARBITRATION_ID_REQUEST = arb_id_request self.ARBITRATION_ID_RESPONSE = arb_id_response self.iso_tp = IsoTp(arb_id_request=self.ARBITRATION_ID_REQUEST, arb_id_response=self.ARBITRATION_ID_RESPONSE, bus=self.bus) def __enter__(self): """ Run server when entering a "with" statement. :return: self """ self.start_server() return self def __exit__(self, exc_type, exc_val, exc_tb): """ Cleanup when leaving a "with" statement. :param exc_type: :param exc_val: :param exc_tb: :return: None """ MockEcu.__exit__(self, None, None, None) self.stop_server() def start_server(self): """ Starts a server process, listening for and responding to incoming ISO-TP messages. Since the server runs in a separate process, this function is non-blocking. :return: None """ self.message_process = multiprocessing.Process(target=self._serve_forever) self.message_process.start() def stop_server(self): """ Stops the server process. :return: None """ MockEcu.__exit__(self, None, None, None) if isinstance(self.message_process, multiprocessing.Process): self.message_process.terminate() self.message_process.join() else: print("stop_server: No server was running") def _serve_forever(self): """ Listens for incoming ISO-TP messages and responds to them. This function is blocking. :return: None """ while True: msg = self.iso_tp.indication() if msg is not None: # ISO-TP message received self.message_handler(msg) def message_handler(self, data): """ Logic for responding to incoming messages :param data: list of data bytes in incoming message :return: None """ # Simulate a small delay before responding time.sleep(self.DELAY_BEFORE_RESPONSE) if data == self.MOCK_SINGLE_FRAME_REQUEST: self.iso_tp.send_response(self.MOCK_SINGLE_FRAME_RESPONSE) elif data == self.MOCK_MULTI_FRAME_TWO_MESSAGES_REQUEST: self.iso_tp.send_response(self.MOCK_MULTI_FRAME_TWO_MESSAGES_RESPONSE) elif data == self.MOCK_MULTI_FRAME_LONG_MESSAGE_REQUEST: self.iso_tp.send_response(self.MOCK_MULTI_FRAME_LONG_MESSAGE_RESPONSE) else: print("Unmapped message in {0}.message_handler:\n {1}".format(self.__class__.__name__, data))
3,462
32.95098
106
py
caringcaribou
caringcaribou-master/caringcaribou/tests/mock/mock_ecu.py
from __future__ import print_function from caringcaribou.utils.can_actions import DEFAULT_INTERFACE import can class MockEcu: """Mock ECU base class, used for running tests over a virtual CAN bus""" DELAY_BEFORE_RESPONSE = 0.01 def __init__(self, bus=None): self.message_process = None if bus is None: self.bus = can.Bus(DEFAULT_INTERFACE) else: self.bus = bus def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.bus.shutdown()
551
23
76
py
caringcaribou
caringcaribou-master/caringcaribou/tests/mock/mock_ecu_uds.py
from caringcaribou.utils.iso15765_2 import IsoTp from caringcaribou.utils.iso14229_1 import * from caringcaribou.utils.common import int_from_byte_list from caringcaribou.tests.mock.mock_ecu import MockEcu from caringcaribou.tests.mock.mock_ecu_iso_tp import MockEcuIsoTp class MockEcuIso14229(MockEcuIsoTp, MockEcu): """ISO-14229-1 (Unified Diagnostic Services) mock ECU handler""" IDENTIFIER_REQUEST_POSITIVE = 0x01 IDENTIFIER_REQUEST_POSITIVE_RESPONSE = 0x72 IDENTIFIER_REQUEST_NEGATIVE = 0x02 REQUEST_IDENTIFIER_VALID = 0xA001 REQUEST_IDENTIFIER_INVALID = 0xA002 REQUEST_VALUE = [0xC0, 0xFF, 0xEE] REQUEST_ADDRESS_LENGTH_AND_FORMAT = 0x22 REQUEST_ADDRESS = 0x0001 REQUEST_DATA_SIZE = 0x10 DATA = list(range(0x14)) # TODO Use dynamic seed value and verify keys using a simple algorithm SECURITY_ACCESS_SEED = [0x36, 0x57] SECURITY_ACCESS_KEY = [0xC9, 0xA9] def __init__(self, arb_id_request, arb_id_response, bus=None): MockEcu.__init__(self, bus) self.ARBITRATION_ID_ISO_14229_REQUEST = arb_id_request self.ARBITRATION_ID_ISO_14229_RESPONSE = arb_id_response # Set CAN filter to only listen to incoming requests on the correct arbitration ID arbitration_id_filter = [{"can_id": arb_id_request, "can_mask": 0x1fffffff}] self.bus.set_filters(arbitration_id_filter) # Setup ISO-TP using the filtered bus self.iso_tp = IsoTp(arb_id_request=self.ARBITRATION_ID_ISO_14229_REQUEST, arb_id_response=self.ARBITRATION_ID_ISO_14229_RESPONSE, bus=self.bus) # Setup diagnostics on top of ISO-TP self.diagnostics = Iso14229_1(tp=self.iso_tp) def __exit__(self, exc_type, exc_val, exc_tb): MockEcuIsoTp.__exit__(self, None, None, None) @staticmethod def create_positive_response(request_service_id, response_data=None): """ Returns data for a positive response of 'request_service_id' with an optional 'response_data' payload :param request_service_id: Service ID (SIDRQ) of the incoming request :param response_data: List of data bytes to transmit in the response :return: List of bytes to be sent as data payload in the response """ # Positive response uses a response service ID (SIDPR) based on the request service ID (SIDRQ) service_response_id = Iso14229_1.get_service_response_id(request_service_id) response = [service_response_id] # Append payload if response_data is not None: response += response_data return response @staticmethod def create_negative_response(request_service_id, nrc): """ Returns data for a negative response of 'request_service_id' with negative response code 'nrc' :param request_service_id: Service ID (SIDRQ) of the incoming request :param nrc: Negative response code (NRC_) :return: List of bytes to be sent as data payload in the response """ response = [Constants.NR_SI, request_service_id, nrc] return response def message_handler(self, data): """ Logic for responding to incoming messages :param data: list of data bytes in incoming message :return: None """ assert isinstance(data, list) try: service_id = data[0] # Handle different services if service_id == ServiceID.DIAGNOSTIC_SESSION_CONTROL: # 0x10 Diagnostic session control response_data = self.handle_diagnostic_session_control(data) elif service_id == ServiceID.ECU_RESET: # 0x11 ECU reset response_data = self.handle_ecu_reset(data) elif service_id == ServiceID.READ_DATA_BY_IDENTIFIER: # 0x22 Read data by identifier response_data = self.handle_read_data_by_identifier(data) elif service_id == ServiceID.READ_MEMORY_BY_ADDRESS: # 0x23 Read memory by address response_data = self.handle_read_memory_by_address(data) elif service_id == ServiceID.SECURITY_ACCESS: # 0x27 Security access response_data = self.handle_security_access(data) elif service_id == ServiceID.WRITE_DATA_BY_IDENTIFIER: # 0x2E Write data by identifier response_data = self.handle_write_data_by_identifier(data) else: # Unsupported service response_data = self.handle_unsupported_service(data) except IndexError: # Parsing failed due to invalid message structure response_data = self.handle_service_error(data) # This check makes it possible to support services where a response should not be sent if response_data is not None: # Simulate a small delay before responding time.sleep(self.DELAY_BEFORE_RESPONSE) self.diagnostics.send_response(response_data) def handle_unsupported_service(self, data): """Provides a standard response for unmapped services, by responding with NRC Service Not Supported""" service_id = data[0] nrc = NegativeResponseCodes.SERVICE_NOT_SUPPORTED response_data = self.create_negative_response(service_id, nrc) return response_data def handle_service_error(self, data): """Provides a standard response for failed service requests""" service_id = data[0] nrc = NegativeResponseCodes.INCORRECT_MESSAGE_LENGTH_OR_INVALID_FORMAT response_data = self.create_negative_response(service_id, nrc) return response_data def handle_diagnostic_session_control(self, data): """Evaluates a diagnostic session control request and returns a response""" service_id = data[0] # TODO Handle different values? session_type = data[1] response_data = self.create_positive_response(service_id) return response_data def handle_read_data_by_identifier(self, data): """ Evaluates a read data by identifier request and returns the appropriate response :param data: Data from incoming request :return: Response to be sent """ service_id = data[0] request = data[2] if request == self.IDENTIFIER_REQUEST_POSITIVE: # Request for positive response # TODO Actually read a parameter from memory payload = [self.IDENTIFIER_REQUEST_POSITIVE_RESPONSE] response_data = self.create_positive_response(service_id, payload) elif request == self.IDENTIFIER_REQUEST_NEGATIVE: # Request for negative response - use Conditions Not Correct nrc = NegativeResponseCodes.CONDITIONS_NOT_CORRECT response_data = self.create_negative_response(service_id, nrc) else: # Unmatched request - use a general reject response nrc = NegativeResponseCodes.GENERAL_REJECT response_data = self.create_negative_response(service_id, nrc) return response_data def handle_write_data_by_identifier(self, data): """ Evaluates a write data by identifier request and returns the appropriate response :param data: Data from incoming request :return: Response to be sent """ service_id = data[0] identifier_start_position = 1 identifier_length = 2 identifier = int_from_byte_list(data, identifier_start_position, identifier_length) request_data = data[3:] # TODO Actually write data to memory if identifier == self.REQUEST_IDENTIFIER_VALID: # Request for positive response # Standard specifies the response payload to be an echo of the data identifier from the request payload = data[identifier_start_position:identifier_start_position + identifier_length] response_data = self.create_positive_response(service_id, payload) elif identifier == self.REQUEST_IDENTIFIER_INVALID: # Request for negative response - use Conditions Not Correct nrc = NegativeResponseCodes.CONDITIONS_NOT_CORRECT response_data = self.create_negative_response(service_id, nrc) else: # Unmatched request - use a general reject response nrc = NegativeResponseCodes.GENERAL_REJECT response_data = self.create_negative_response(service_id, nrc) return response_data def handle_read_memory_by_address(self, data): """ Evaluates a read memory by address request and returns the appropriate response :param data: Data from incoming request :return: Response to be sent """ service_id = data[0] address_field_size = (data[1] >> 4) & 0xF data_length_field_size = (data[1] & 0xF) address_start_position = 2 data_length_start_position = 4 start_address = int_from_byte_list(data, address_start_position, address_field_size) data_length = int_from_byte_list(data, data_length_start_position, data_length_field_size) end_address = start_address + data_length if 0 <= start_address <= end_address <= len(self.DATA): memory_data = self.DATA[start_address:end_address] response_data = self.create_positive_response(service_id, memory_data) else: nrc = NegativeResponseCodes.REQUEST_OUT_OF_RANGE response_data = self.create_negative_response(service_id, nrc) return response_data def handle_ecu_reset(self, data): """ Evaluates an ECU reset request and returns the appropriate response :param data: Data from incoming request :return: Response to be sent """ service_id = data[0] subfunction = data[1] reset_type = subfunction & 0x7F suppress_positive_response = subfunction >> 7 reset_types = Services.EcuReset.ResetType if reset_type in [reset_types.HARD_RESET, reset_types.KEY_OFF_ON_RESET, reset_types.SOFT_RESET]: if suppress_positive_response: response_data = None else: response_data = self.create_positive_response(service_id, [reset_type]) else: nrc = NegativeResponseCodes.SUB_FUNCTION_NOT_SUPPORTED response_data = self.create_negative_response(service_id, nrc) return response_data def handle_security_access(self, data): """ Evaluates security access requests (both "Request seed" and "Send key") and returns the appropriate response :param data: Data from incoming request :return: Response to be sent """ service_id = data[0] subfunction = data[1] level = subfunction & 0x7F service_handler = Services.SecurityAccess.RequestSeedOrSendKey() if service_handler.is_valid_request_seed_level(level): # Request seed handling payload = [level] payload.extend(self.SECURITY_ACCESS_SEED) response_data = self.create_positive_response(service_id, payload) elif service_handler.is_valid_send_key_level(level): # Send key handling expected_key = self.SECURITY_ACCESS_KEY received_key = data[2:] if received_key == expected_key: # Correct key response_data = self.create_positive_response(service_id, [level]) else: # Invalid key nrc = NegativeResponseCodes.INVALID_KEY response_data = self.create_negative_response(service_id, nrc) else: # Unsupported subfunction nrc = NegativeResponseCodes.SUB_FUNCTION_NOT_SUPPORTED response_data = self.create_negative_response(service_id, nrc) return response_data
12,194
43.025271
116
py
caringcaribou
caringcaribou-master/caringcaribou/tests/mock/__init__.py
0
0
0
py
caringcaribou
caringcaribou-master/caringcaribou/utils/iso15765_2.py
from caringcaribou.utils.can_actions import DEFAULT_INTERFACE from caringcaribou.utils.constants import ARBITRATION_ID_MAX_EXTENDED, ARBITRATION_ID_MAX import can import datetime import time class IsoTp: """ Implementation of ISO-15765-2, also known as ISO-TP. This is a multi-frame messaging protocol over CAN, which allows message payloads of up to 4095 bytes. """ MAX_SF_LENGTH = 7 MAX_FF_LENGTH = 6 MAX_CF_LENGTH = 7 SF_PCI_LENGTH = 1 CF_PCI_LENGTH = 1 FF_PCI_LENGTH = 2 FC_PCI_LENGTH = 3 FC_FS_CTS = 0 FC_FS_WAIT = 1 FC_FS_OVFLW = 2 SF_FRAME_ID = 0 FF_FRAME_ID = 1 CF_FRAME_ID = 2 FC_FRAME_ID = 3 N_BS_TIMEOUT = 1.5 MAX_FRAME_LENGTH = 8 MAX_MESSAGE_LENGTH = 4095 def __init__(self, arb_id_request, arb_id_response, bus=None, padding_value=0x00): # Setting default bus to None rather than the actual bus prevents a CanError when # called with a virtual CAN bus, while the OS is lacking a working CAN interface if bus is None: self.bus = can.Bus(DEFAULT_INTERFACE) else: self.bus = bus self.arb_id_request = arb_id_request self.arb_id_response = arb_id_response # Controls optional padding of SF messages and the last CF frame in multi-frame messages # Disabled padding is _not_ part of ISO-15765-2, but might prove useful for testing against some targets self.padding_value = padding_value if padding_value is None: self.padding_enabled = False else: self.padding_enabled = True if not isinstance(padding_value, int): raise TypeError("IsoTp: padding must be an integer or None, received '{0}'".format(padding_value)) if not 0x00 <= padding_value <= 0xFF: raise ValueError("IsoTp: padding must be in range 0x00-0xFF (0-255), got '{0}'".format(padding_value)) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.bus.shutdown() def _set_filters(self, filters): """ Sets filters for the CAN bus - description can be found at https://python-can.readthedocs.io/en/stable/bus.html#can.BusABC.set_filters :param filters: dict specifying "can_id", "can_mask" and (optional) "extended" flag :return: None """ self.bus.set_filters(filters) def set_filter_single_arbitration_id(self, arbitration_id): """Set a filter to only receive incoming messages on 'arbitration_id'""" arbitration_id_filter = [{"can_id": arbitration_id, "can_mask": ARBITRATION_ID_MAX_EXTENDED}] self._set_filters(arbitration_id_filter) def clear_filters(self): """Remove arbitration ID filters""" self._set_filters(None) def send_message(self, data, arbitration_id, force_extended=False): """ Transmits a message using 'arbitration_id' and 'data' on 'self.bus' :param data: Data to send :param arbitration_id: Arbitration ID to use :param force_extended: Force extended arbitration ID :return: None """ is_extended = force_extended or arbitration_id > ARBITRATION_ID_MAX msg = can.Message(arbitration_id=arbitration_id, data=data, is_extended_id=is_extended) self.bus.send(msg) def decode_sf(self, frame): """ Decodes a singe frame (SF) message :param frame: Frame to decode :return: Tuple of single frame data length (SF_DL) and data if valid, Tuple of None, None otherwise """ if len(frame) >= self.SF_PCI_LENGTH: sf_dl = frame[0] & 0xF data = frame[1:] return sf_dl, list(data) else: return None, None def decode_ff(self, frame): """ Decodes a first frame (FF) message :param frame: Frame to decode :return: Tuple of first frame data length (FF_DL) and data if valid, Tuple of None, None otherwise """ if len(frame) >= self.FF_PCI_LENGTH: ff_dl = ((frame[0] & 0xF) << 8) | frame[1] data = frame[2:] return ff_dl, list(data) else: return None, None def decode_cf(self, frame): """ Decodes a consecutive frame (CF) message :param frame: Frame to decode :return: Tuple of sequence number (SN) and data if valid, Tuple of None, None otherwise """ if len(frame) >= self.CF_PCI_LENGTH: sn = frame[0] & 0xF data = frame[1:] return sn, list(data) else: return None, None def decode_fc(self, frame): """ Decodes a flow control (FC) frame :param frame: Frame to decode :return: Tuple of values flow status (FS), block size (BS) and separation time minimum (STmin) if valid, Tuple of None, None, None otherwise """ if len(frame) >= self.FC_PCI_LENGTH: fs = frame[0] & 0xF block_size = frame[1] st_min = frame[2] return fs, block_size, st_min else: return None, None, None def encode_fc(self, flow_status, block_size, st_min): """ Encodes a flow control (FC) message :param flow_status: Flow status (FS) :param block_size: Block size (BS) :param st_min: Separation time minimum (STmin) :return: Encoded data for the flow control message """ return [(self.FC_FRAME_ID << 4) | flow_status, block_size, st_min, 0, 0, 0, 0, 0] def send_request(self, message): """ Wrapper for sending 'message' as a request :param message: The message to send :return: None """ frames = self.get_frames_from_message(message, padding_value=self.padding_value) self.transmit(frames, self.arb_id_request, self.arb_id_response) def send_response(self, message): """ Wrapper for sending 'message' as a response :param message: The message to send :return: None """ frames = self.get_frames_from_message(message, padding_value=self.padding_value) self.transmit(frames, self.arb_id_response, self.arb_id_request) def indication(self, wait_window=None, trim_padding=True, first_frame_only=False): """ Receives an ISO-15765-2 message (one or more frames) and returns its content. :param wait_window: Max time (in seconds) to wait before timeout :param trim_padding: If True, removes message padding bytes from the received message :param first_frame_only: If True, return first frame only (simulating overflow behavior for multi-frame message) :return: A list of received data bytes if successful, None otherwise """ message = [] if wait_window is None: wait_window = self.N_BS_TIMEOUT start_time = datetime.datetime.now() end_time = start_time + datetime.timedelta(seconds=wait_window) sn = 0 message_length = 0 while True: # Timeout check current_time = datetime.datetime.now() if current_time >= end_time: # Timeout return None # Receive frame msg = self.bus.recv(wait_window) if msg is not None: if msg.arbitration_id == self.arb_id_request: flow_control_arbitration_id = self.arb_id_response elif msg.arbitration_id == self.arb_id_response: flow_control_arbitration_id = self.arb_id_request else: # Unknown arbitration ID - ignore message continue frame = msg.data if len(frame) > 0: frame_type = (frame[0] >> 4) & 0xF if frame_type == self.SF_FRAME_ID: # Single frame (SF) dl, message = self.decode_sf(frame) if trim_padding: # Trim padding, in case the data exceeds single frame data length (SF_DL) message = message[:dl] break elif frame_type == self.FF_FRAME_ID: # First frame (FF) of a multi-frame message message_length, message = self.decode_ff(frame) if first_frame_only: # This is a hack to make it possible to only retrieve the first frame of a multi-frame # response, by telling the sender to stop sending data due to overflow ovflw_frame = self.encode_fc(self.FC_FS_OVFLW, 0, 0) # Respond with overflow (OVFLW) message self.send_message(ovflw_frame, flow_control_arbitration_id) # Return the first frame only break fc_frame = self.encode_fc(self.FC_FS_CTS, 0, 0) sn = 0 # Respond with flow control (FC) message self.send_message(fc_frame, flow_control_arbitration_id) elif frame_type == self.CF_FRAME_ID: # Consecutive frame (CF) new_sn, data = self.decode_cf(frame) if (sn + 1) % 16 == new_sn: sn = new_sn message += data if len(message) >= message_length: # Last frame received if trim_padding: # Trim padding of last frame, which may exceed first frame data length (FF_DL) message = message[:message_length] # Stop listening for more frames break else: pass else: # Invalid frame type return None return list(message) def transmit(self, frames, arbitration_id, arbitration_id_flow_control): """ Transmits 'frames' in order on the bus, according to ISO-15765-2 :param frames: List of frames (which are in turn lists of values) to send :param arbitration_id: The arbitration ID used for sending :param arbitration_id_flow_control: The arbitration ID used for receiving flow control (FC) :return: None """ if len(frames) == 0: # No data to send return None elif len(frames) == 1: # Single frame self.send_message(frames[0], arbitration_id) elif len(frames) > 1: # Multiple frames frame_index = 0 # Send first frame (FF) self.send_message(frames[frame_index], arbitration_id) number_of_frames_left_to_send = len(frames) - 1 number_of_frames_left_to_send_in_block = 0 frame_index += 1 st_min = 0 while number_of_frames_left_to_send > 0: receiver_is_ready = False while not receiver_is_ready: # Wait for receiver to send flow control (FC) msg = self.bus.recv(self.N_BS_TIMEOUT) if msg is None: # Quit on timeout return None # Verify that msg uses the expected arbitration ID elif msg.arbitration_id != arbitration_id_flow_control: continue fc_frame = msg.data # Decode Flow Status (FS) from FC message fs, block_size, st_min = self.decode_fc(fc_frame) if fs == self.FC_FS_WAIT: # Flow status (FS) wait (WT) continue elif fs == self.FC_FS_CTS: # Continue to send (CTS) receiver_is_ready = True number_of_frames_left_to_send_in_block = block_size if number_of_frames_left_to_send < number_of_frames_left_to_send_in_block or block_size == 0: number_of_frames_left_to_send_in_block = number_of_frames_left_to_send # If STmin is specified in microseconds (0xF1-0xF9) or using reserved ranges (0x80-0xF0 and # 0xFA-0xFF), round up to one millisecond if st_min > 0x7F: st_min = 1 elif fs == self.FC_FS_OVFLW: # Overflow - abort transmission return None else: # Timeout - did not receive a CTS message in time return None while number_of_frames_left_to_send_in_block > 0: # Send more frames, until it is time to wait for flow control (FC) again self.send_message(frames[frame_index], arbitration_id) frame_index += 1 number_of_frames_left_to_send_in_block -= 1 number_of_frames_left_to_send -= 1 if number_of_frames_left_to_send_in_block > 0: time.sleep(st_min / 1000) @staticmethod def get_frames_from_message(message, padding_value=0x00): """ Returns a copy of 'message' split into frames, :param message: Message to split :param padding_value: Integer value used to pad messages, or None to disable padding (not part of ISO-15765-3) :return: List of frames """ if padding_value is None: padding_enabled = False padding_value = 0x00 else: padding_enabled = True frame_list = [] message_length = len(message) if message_length > IsoTp.MAX_MESSAGE_LENGTH: error_msg = "Message too long for ISO-TP. Max allowed length is {0} bytes, received {1} bytes".format( IsoTp.MAX_MESSAGE_LENGTH, message_length) raise ValueError(error_msg) if message_length <= IsoTp.MAX_SF_LENGTH: # Single frame (SF) message if padding_enabled: frame = [padding_value] * IsoTp.MAX_FRAME_LENGTH else: frame = [padding_value] * (message_length + 1) frame[0] = (IsoTp.SF_FRAME_ID << 4) | message_length for i in range(0, message_length): frame[1 + i] = message[i] frame_list.append(frame) else: # Multiple frame message bytes_left_to_copy = message_length # Create first frame (FF) frame = [padding_value] * IsoTp.MAX_FRAME_LENGTH frame[0] = (IsoTp.FF_FRAME_ID << 4) | (message_length >> 8) frame[1] = message_length & 0xFF for i in range(0, IsoTp.MAX_FF_LENGTH): frame[2 + i] = message[i] frame_list.append(frame) # Create consecutive frames (CF) bytes_copied = IsoTp.MAX_FF_LENGTH bytes_left_to_copy -= bytes_copied sn = 0 while bytes_left_to_copy > 0: sn = (sn + 1) % 16 if not padding_enabled and bytes_left_to_copy < 7: # Skip padding on last CF frame = [padding_value] * (bytes_left_to_copy + 1) else: frame = [padding_value] * IsoTp.MAX_FRAME_LENGTH frame[0] = (IsoTp.CF_FRAME_ID << 4) | sn # Fill current CF bytes_to_copy_to_current_cf = min(IsoTp.MAX_CF_LENGTH, bytes_left_to_copy) for i in range(bytes_to_copy_to_current_cf): frame[1 + i] = message[bytes_copied] bytes_left_to_copy = bytes_left_to_copy - 1 bytes_copied = bytes_copied + 1 frame_list.append(frame) return frame_list
16,493
40.756962
120
py
caringcaribou
caringcaribou-master/caringcaribou/utils/constants.py
ARBITRATION_ID_MIN = 0x0 ARBITRATION_ID_MAX = 0x7FF ARBITRATION_ID_MAX_EXTENDED = 0x1FFFFFFF BYTE_MIN = 0x00 BYTE_MAX = 0xFF
127
15
40
py
caringcaribou
caringcaribou-master/caringcaribou/utils/can_actions.py
from __future__ import print_function from caringcaribou.utils.constants import ARBITRATION_ID_MAX, ARBITRATION_ID_MAX_EXTENDED, ARBITRATION_ID_MIN, BYTE_MAX, BYTE_MIN from sys import stdout, version_info import can import time # Handle large ranges efficiently in both python 2 and 3 if version_info[0] == 2: range = xrange MESSAGE_DELAY = 0.1 DELAY_STEP = 0.02 NOTIFIER_STOP_DURATION = 0.5 # Global CAN interface setting, which can be set through the -i flag to cc.py # The value None corresponds to the default CAN interface (typically can0) DEFAULT_INTERFACE = None def auto_blacklist(bus, duration, classifier_function, print_results): """Listens for false positives on the CAN bus and generates an arbitration ID blacklist. Finds all can.Message <msg> on 'bus' where 'classifier_function(msg)' evaluates to True. Terminates after 'duration' seconds and returns a set of all matching arbitration IDs. Prints progress, time countdown and list of results if 'print_results' is True. :param bus: CAN bus instance :param duration: duration in seconds :param classifier_function: function which, when called upon a can.Message instance, returns a bool indicating if it should be blacklisted :param print_results: whether progress and results should be printed to stdout :type bus: can.Bus :type duration: float :type classifier_function: function :type print_results: bool :return set of matching arbitration IDs to blacklist :rtype set(int) """ if print_results: print("Scanning for arbitration IDs to blacklist") blacklist = set() start_time = time.time() end_time = start_time + duration while time.time() < end_time: if print_results: time_left = end_time - time.time() num_matches = len(blacklist) print("\r{0:> 5.1f} seconds left, {1} found".format(time_left, num_matches), end="") stdout.flush() # Receive message msg = bus.recv(0.1) if msg is None: continue # Classify if classifier_function(msg): # Add to blacklist blacklist.add(msg.arbitration_id) if print_results: num_matches = len(blacklist) print("\r 0.0 seconds left, {0} found".format(num_matches), end="") if len(blacklist) > 0: print("\n Detected IDs: {0}".format(" ".join(sorted(list(map(hex, blacklist)))))) else: print() return blacklist class CanActions: def __init__(self, arb_id=None, notifier_enabled=True): """ CanActions constructor :param arb_id: int default arbitration ID for object or None :param notifier_enabled: bool indicating whether a notifier for incoming message callbacks should be enabled """ self.bus = can.Bus(DEFAULT_INTERFACE) self.arb_id = arb_id self.bruteforce_running = False self.notifier = None if notifier_enabled: self.enable_notifier() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if self.notifier is not None: self.disable_notifier() self.bus.shutdown() def enable_notifier(self): self.notifier = can.Notifier(self.bus, listeners=[]) def disable_notifier(self): self.clear_listeners() # Prevent threading errors by stopping notifier gracefully self.notifier.stop(NOTIFIER_STOP_DURATION) self.notifier = None def add_listener(self, listener): self.notifier.listeners.append(listener) def clear_listeners(self): self.notifier.listeners = [] def set_listener(self, listener): self.clear_listeners() self.add_listener(listener) def send(self, data, arb_id=None, is_extended=None, is_error=False, is_remote=False): if len(data) > 8: raise IndexError("Invalid CAN message length: {0}".format(len(data))) # Fallback to default arbitration ID (self.arb_id) if no other ID is specified if arb_id is None: if self.arb_id is None: raise ValueError("Arbitration ID must be set through either 'arb_id' argument or self.arb_id") arb_id = self.arb_id # Force extended flag if it is unspecified and arbitration ID is larger than the standard format allows if is_extended is None: is_extended = arb_id > ARBITRATION_ID_MAX msg = can.Message(arbitration_id=arb_id, data=data, is_extended_id=is_extended, is_error_frame=is_error, is_remote_frame=is_remote) self.bus.send(msg) def bruteforce_arbitration_id(self, data, callback, min_id, max_id, callback_end=None): # Set limits if min_id is None: min_id = ARBITRATION_ID_MIN if max_id is None: if min_id <= ARBITRATION_ID_MAX: max_id = ARBITRATION_ID_MAX else: # If min_id is extended, use an extended default max_id as well max_id = ARBITRATION_ID_MAX_EXTENDED # Sanity checks if min_id > max_id: if callback_end: callback_end("Invalid range: min > max") return # Start bruteforce self.bruteforce_running = True for arb_id in range(min_id, max_id + 1): self.notifier.listeners = [callback(arb_id)] # Use standard addressing (11 bits arbitration ID) instead of extended (29 bits) when possible extended = False if arb_id > ARBITRATION_ID_MAX: extended = True msg = can.Message(arbitration_id=arb_id, data=data, is_extended_id=extended) self.bus.send(msg) time.sleep(MESSAGE_DELAY) # Return if stopped by calling module if not self.bruteforce_running: self.clear_listeners() return # Callback if bruteforce finished without being stopped if callback_end: self.clear_listeners() callback_end("Bruteforce of range 0x{0:x}-0x{1:x} completed".format(min_id, max_id)) def bruteforce_data(self, data, bruteforce_index, callback, min_value=BYTE_MIN, max_value=BYTE_MAX, callback_end=None): self.bruteforce_running = True for value in range(min_value, max_value + 1): self.notifier.listeners = [callback(value)] data[bruteforce_index] = value self.send(data) time.sleep(MESSAGE_DELAY) if not self.bruteforce_running: self.notifier.listeners = [] return if callback_end: self.notifier.listeners = [] callback_end() def bruteforce_data_new(self, data, bruteforce_indices, callback, min_value=BYTE_MIN, max_value=BYTE_MAX, callback_done=None): def send(msg_data, idxs): self.notifier.listeners = [callback(["{0:02x}".format(msg_data[a]) for a in idxs])] self.send(msg_data) self.current_delay = 0.2 while self.current_delay > 0.0: time.sleep(DELAY_STEP) self.current_delay -= DELAY_STEP if not self.bruteforce_running: self.notifier.listeners = [] return def bruteforce(idx): if idx >= len(bruteforce_indices): send(data, bruteforce_indices) return for i in range(min_value, max_value + 1): data[bruteforce_indices[idx]] = i bruteforce(idx + 1) # Make sure that the data array is correctly initialized for the bruteforce for idx_i in bruteforce_indices: data[idx_i] = 0 bruteforce(0) if callback_done: callback_done("Scan finished") def send_single_message_with_callback(self, data, callback): self.set_listener(callback) self.send(data) def bruteforce_stop(self): self.bruteforce_running = False
8,331
37.574074
129
py
caringcaribou
caringcaribou-master/caringcaribou/utils/iso14229_1.py
import time # Fix for backward compatibility with Python versions older than 3.3, # where time.process_time is not available try: time.process_time except AttributeError: time.process_time = time.clock class DynamicallyDefinedIdentifierArg(object): def __init__(self, source_data_identifier, position_in_source_data_record, memory_size): self.sourceDataIdentifier = source_data_identifier self.positionInSourceDataRecord = position_in_source_data_record self.memorySize = memory_size class NegativeResponseCodes(object): """ ISO-14229-1 negative response codes """ POSITIVE_RESPONSE = 0x00 # 0x01-0x0F ISO SAE Reserved GENERAL_REJECT = 0x10 SERVICE_NOT_SUPPORTED = 0x11 SUB_FUNCTION_NOT_SUPPORTED = 0x12 INCORRECT_MESSAGE_LENGTH_OR_INVALID_FORMAT = 0x13 RESPONSE_TOO_LONG = 0x14 # 0x15-0x20 ISO SAE Reserved BUSY_REPEAT_REQUEST = 0x21 CONDITIONS_NOT_CORRECT = 0x22 # 0x23 ISO SAE Reserved REQUEST_SEQUENCE_ERROR = 0x24 NO_RESPONSE_FROM_SUBNET_COMPONENT = 0x25 FAILURE_PREVENTS_EXECUTION_OF_REQUESTED_ACTION = 0x26 # 0x27-0x30 ISO SAE Reserved REQUEST_OUT_OF_RANGE = 0x31 # 0x32 ISO SAE Reserved SECURITY_ACCESS_DENIED = 0x33 # 0x34 ISO SAE Reserved INVALID_KEY = 0x35 EXCEEDED_NUMBER_OF_ATTEMPTS = 0x36 REQUIRED_TIME_DELAY_NOT_EXPIRED = 0x37 # 0x38-0x4F Reserved by extended data link security document # 0x50-0x6F ISO SAE Reserved UPLOAD_DOWNLOAD_NOT_ACCEPTED = 0x70 TRANSFER_DATA_SUSPENDED = 0x71 GENERAL_PROGRAMMING_FAILURE = 0x72 WRONG_BLOCK_SEQUENCE_COUNTER = 0x73 # 0x74-0x77 ISO SAE Reserved REQUEST_CORRECTLY_RECEIVED_RESPONSE_PENDING = 0x78 # 0x79-0x7D ISO SAE Reserved SUB_FUNCTION_NOT_SUPPORTED_IN_ACTIVE_SESSION = 0x7E SERVICE_NOT_SUPPORTED_IN_ACTIVE_SESSION = 0x7F # 0x80 ISO SAE Reserved RPM_TOO_HIGH = 0x81 RPM_TOO_LOW = 0x82 ENGINE_IS_RUNNING = 0x83 ENGINE_IS_NOT_RUNNING = 0x84 ENGINE_RUN_TIME_TOO_LOW = 0x85 TEMPERATURE_TOO_HIGH = 0x86 TEMPERATURE_TOO_LOW = 0x87 VEHICLE_SPEED_TOO_HIGH = 0x88 VEHICLE_SPEED_TOO_LOW = 0x89 THROTTLE_PEDAL_TOO_HIGH = 0x8A THROTTLE_PEDAL_TOO_LOW = 0x8B TRANSMISSION_RANGE_NOT_IN_NEUTRAL = 0x8C TRANSMISSION_RANGE_NOT_IN_GEAR = 0x8D # 0x8E ISO SAE Reserved BRAKE_SWITCHES_NOT_CLOSED = 0x8F SHIFT_LEVER_NOT_IN_PARK = 0x90 TORQUE_CONVERTER_CLUTCH_LOCKED = 0x91 VOLTAGE_TOO_HIGH = 0x92 VOLTAGE_TOO_LOW = 0x93 # 0x94-0xEF Reserved for specific conditions not correct # 0xF0-0xFE Vehicle manufacturer specific conditions not correct # 0xFF ISO SAE Reserved class ServiceID(object): """ ISO-14229-1 service ID definitions """ DIAGNOSTIC_SESSION_CONTROL = 0x10 ECU_RESET = 0x11 CLEAR_DIAGNOSTIC_INFORMATION = 0x14 READ_DTC_INFORMATION = 0x19 READ_DATA_BY_IDENTIFIER = 0x22 READ_MEMORY_BY_ADDRESS = 0x23 READ_SCALING_DATA_BY_IDENTIFIER = 0x24 SECURITY_ACCESS = 0x27 COMMUNICATION_CONTROL = 0x28 READ_DATA_BY_PERIODIC_IDENTIFIER = 0x2A DYNAMICALLY_DEFINE_DATA_IDENTIFIER = 0x2C WRITE_DATA_BY_IDENTIFIER = 0x2E INPUT_OUTPUT_CONTROL_BY_IDENTIFIER = 0x2F ROUTINE_CONTROL = 0x31 REQUEST_DOWNLOAD = 0x34 REQUEST_UPLOAD = 0x35 TRANSFER_DATA = 0x36 REQUEST_TRANSFER_EXIT = 0x37 REQUEST_FILE_TRANSFER = 0x38 WRITE_MEMORY_BY_ADDRESS = 0x3D TESTER_PRESENT = 0x3E ACCESS_TIMING_PARAMETER = 0x83 SECURED_DATA_TRANSMISSION = 0x84 CONTROL_DTC_SETTING = 0x85 RESPONSE_ON_EVENT = 0x86 LINK_CONTROL = 0x87 class BaseService(object): """Base class for services""" service_id = None class Services(object): """Class structure containing service specific constants, sub-function parameters and functions""" class DiagnosticSessionControl(BaseService): service_id = ServiceID.DIAGNOSTIC_SESSION_CONTROL class DiagnosticSessionType(object): # 0x00 ISO SAE Reserved DEFAULT_SESSION = 0x01 PROGRAMMING_SESSION = 0x02 EXTENDED_DIAGNOSTIC_SESSION = 0x03 SAFETY_SYSTEM_DIAGNOSTIC_SESSION = 0x04 # 0x05-0x3F ISO SAE Reserved # 0x40-0x5F Vehicle manufacturer specific VEHICLE_MANUFACTURER_SESSION_MIN = 0x40 VEHICLE_MANUFACTURER_SESSION_MAX = 0x5F # 0x60-0x7E System supplier specific SYSTEM_SUPPLIER_SESSION_MIN = 0x60 SYSTEM_SUPPLIER_SESSION_MAX = 0x7E # 0x7F ISO SAE Reserved class EcuReset(BaseService): service_id = ServiceID.ECU_RESET class ResetType(object): # 0x00 ISO SAE Reserved HARD_RESET = 0x01 KEY_OFF_ON_RESET = 0x02 SOFT_RESET = 0x03 ENABLE_RAPID_POWER_SHUTDOWN = 0x04 DISABLE_RAPID_POWER_SHUTDOWN = 0x05 # 0x06-0x3F ISO SAE Reserved # 0x40-0x5F Vehicle manufacturer specific # 0x60-0x7E System supplier specific # 0x7F ISO SAE Reserved class SecurityAccess(BaseService): service_id = ServiceID.SECURITY_ACCESS class RequestSeedOrSendKey(object): """ These are lined up so that value X "request seed level N" has a matching "send key level N" at value X+1. 0x01 is Request seed level 0x01 0x02 is Send key level 0x01 0x03 is Request seed level 0x02 0x04 is Send key level 0x02 (...) 0x41 is Request seed level 0x21 0x42 is Send key level 0x21 The security levels numbering is arbitrary and does not imply any relationship between the levels. """ # 0x00 ISO SAE Reserved # 0x01-0x42 Vehicle manufacturer specific request # seed/send key pairs # 0x43-0X5E ISO SAE Reserved ISO_26021_2_VALUES = 0x5F ISO_26021_2_SEND_KEY = 0x60 # 0x61-0x7E System supplier specific # 0x7F ISO SAE Reserved __REQUEST_SEED_MIN = 0x01 __REQUEST_SEED_MAX = 0x41 __SEND_KEY_MIN = 0x02 __SEND_KEY_MAX = 0x42 def is_valid_request_seed_level(self, sub_function): """Returns True if 'sub_function' is a valid request seed value and False otherwise""" value = sub_function & 0x7F valid_interval = (self.__REQUEST_SEED_MIN <= value <= self.__REQUEST_SEED_MAX) is_odd = value % 2 == 1 return valid_interval and is_odd def is_valid_send_key_level(self, sub_function): """Returns True if 'sub_function' is a valid send key value and False otherwise""" value = sub_function & 0x7F valid_interval = (self.__SEND_KEY_MIN <= value <= self.__SEND_KEY_MAX) is_even = value % 2 == 0 return valid_interval and is_even @staticmethod def get_send_key_for_request_seed(seed): return seed + 1 class TesterPresent(BaseService): service_id = ServiceID.TESTER_PRESENT class Constants(object): # NR_SI (Negative Response Service Identifier) is a bit special, since # it is not a service per se. # From ISO-14229-1 specification: "The NR_SI value is co-ordinated with # the SI values. The NR_SI value is not used as a SI value in order to # make A_Data coding and decoding easier." NR_SI = 0x7F class Iso14229_1(object): P3_CLIENT = 5 def __init__(self, tp): self.tp = tp def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): pass @staticmethod def get_service_response_id(request_id): """ Returns the service response ID for the given request ID :param request_id: Request service ID :return: Corresponding response service ID """ return request_id + 0x40 @staticmethod def get_service_request_id(response_id): """ Returns the service request ID for the given response ID :param response_id: Response service ID :return: Corresponding request service ID """ return response_id - 0x40 def send_request(self, data): """ Sends a request message containing 'data' through the underlying TP layer :param data: The data to send :return: None """ return self.tp.send_request(data) def send_response(self, data): """ Sends a response message containing 'data' through the underlying TP layer :param data: The data to send :return: None """ return self.tp.send_response(data) def receive_response(self, wait_window): """ Attempts to receive a response through the underlying TP layer :param wait_window: Minimum time (in seconds) to wait before timeout :return: The received response if successful, None otherwise """ start_time = time.process_time() while True: current_time = time.process_time() if (current_time - start_time) > wait_window: return None response = self.tp.indication(wait_window) NRC = NegativeResponseCodes NRC_RCRRP = NRC.REQUEST_CORRECTLY_RECEIVED_RESPONSE_PENDING if response is not None and len(response) >= 3: if (response[0] == Constants.NR_SI and response[2] == NRC_RCRRP): continue break return response @staticmethod def is_positive_response(response): """ Returns a bool indicating whether 'response' is positive :param response: ISO-14229-1 response data :return: False if response is a NEGATIVE_RESPONSE, True otherwise """ if (response is not None and len(response) > 0 and response[0] != Constants.NR_SI): return True return False def read_data_by_identifier(self, identifier): """ Sends a "read data by identifier" request for 'identifier' :param identifier: Data identifier :return: Response data if successful, None otherwise """ response = [] num_dids = len(identifier) if num_dids > 0: request = [0] * ((num_dids * 2) + 1) request[0] = ServiceID.READ_DATA_BY_IDENTIFIER for i in range(0, num_dids): request[i * 2 + 1] = (identifier[i] >> 8) & 0xFF request[i * 2 + 2] = identifier[i] & 0xFF self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response def read_memory_by_address(self, address_and_length_format, memory_address, memory_size): """ Sends a "read memory by address" request for 'memory_address' :param address_and_length_format: Address and length format :param memory_address: Memory address :param memory_size: Memory size :return: Response data if successful, None otherwise """ addr_sz_fmt = (address_and_length_format >> 4) & 0xF data_sz_fmt = (address_and_length_format & 0xF) request = [0] * (1 + 1 + addr_sz_fmt + data_sz_fmt) request[0] = ServiceID.READ_MEMORY_BY_ADDRESS request[1] = address_and_length_format offset = 2 for i in (range(0, addr_sz_fmt)): request[addr_sz_fmt + offset - i - 1] = (memory_address & 0xFF) memory_address = (memory_address >> 8) offset += addr_sz_fmt for i in (range(0, data_sz_fmt)): request[data_sz_fmt + offset - i - 1] = (memory_size & 0xFF) memory_size = (memory_size >> 8) self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response def write_memory_by_address(self, address_and_length_format, memory_address, memory_size, data): """ Sends a "write memory by address" request to write 'data' to 'memory_address' :param address_and_length_format: Address and length format :param memory_address: Memory address :param memory_size: Memory size :param data: The data to write to 'memory_address' :return: Response data if successful, None otherwise """ addr_sz_fmt = (address_and_length_format >> 4) & 0xF data_sz_fmt = (address_and_length_format & 0xF) request = [0] * (1 + 1 + addr_sz_fmt + data_sz_fmt) request[0] = ServiceID.WRITE_MEMORY_BY_ADDRESS request[1] = address_and_length_format offset = 2 for i in (range(0, addr_sz_fmt)): request[addr_sz_fmt + offset - i - 1] = (memory_address & 0xFF) memory_address = (memory_address >> 8) offset += addr_sz_fmt for i in (range(0, data_sz_fmt)): request[data_sz_fmt + offset - i - 1] = (memory_size & 0xFF) memory_size = (memory_size >> 8) request += data self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response def write_data_by_identifier(self, identifier, data): """ Sends a "write data by identifier" request to write 'data' to 'identifier' :param identifier: Data identifier :param data: Data to write to 'identifier' :return: Response data if successful, None otherwise """ request = [0] * (1 + 2) request[0] = ServiceID.WRITE_DATA_BY_IDENTIFIER request[1] = (identifier >> 8) & 0xFF request[2] = identifier & 0xFF request += data self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response def input_output_control_by_identifier(self, identifier, data): """ Sends a "input output control by identifier" request for 'data' to 'identifier' :param identifier: Data identifier :param data: Data :return: Response data if successful, None otherwise """ request = [0] * (1 + 2) request[0] = ServiceID.INPUT_OUTPUT_CONTROL_BY_IDENTIFIER request[1] = (identifier >> 8) & 0xFF request[2] = identifier & 0xFF request += data self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response def dynamically_define_data_identifier(self, identifier, sub_function, sub_function_arg): """ Sends a "dynamically define data identifier" request for 'identifier' :param identifier: DDDID to set :param sub_function: Sub function :param sub_function_arg: Sub function arguments :return: Response data if successful, None otherwise """ if (identifier is None or sub_function is None or sub_function_arg is None): return None request = [0] * (1 + 1 + 2 + len(sub_function_arg) * 4) request[0] = ServiceID.DYNAMICALLY_DEFINE_DATA_IDENTIFIER request[1] = sub_function request[2] = (identifier >> 8) & 0xFF request[3] = identifier & 0xFF offset = 4 for did in sub_function_arg: request[offset + 0] = (did.sourceDataIdentifier >> 8) & 0xFF request[offset + 1] = did.sourceDataIdentifier & 0xFF request[offset + 2] = did.positionInSourceDataRecord request[offset + 3] = did.memorySize offset += 4 self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response def diagnostic_session_control(self, session_type): """ Sends a "DiagnosticSessionControl" request for specified session type :param session_type: Indicates which kind of session should be requested :return: Response data if successful, None otherwise """ request = [0] * 2 request[0] = ServiceID.DIAGNOSTIC_SESSION_CONTROL request[1] = session_type self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response def ecu_reset(self, reset_type): """ Sends an "ECU reset" request for specified reset type :param reset_type: Indicates which kind of reset should be requested :return: Response data if successful, None otherwise """ request = [0] * 2 request[0] = ServiceID.ECU_RESET request[1] = reset_type self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response def security_access_request_seed(self, level, data_record=None): """ Sends a Security Access "Request seed" message for 'level' :param level: Security Access Type level to send request seed for :param data_record: Optional data to transmit when requesting seed, e.g. client identification :return: Response data (containing seed) if successful, None otherwise """ service_id = ServiceID.SECURITY_ACCESS request = [service_id, level] if data_record: for data_record in data_record: request.append(data_record) self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response def security_access_send_key(self, level, key): """ Sends a Security Access "Send key" message with 'key' for 'level' :param level: Security Access Type level to send key for :param key: Key to transmit :return: Response data if successful, None otherwise """ service_id = ServiceID.SECURITY_ACCESS request = [service_id, level] for key_byte in key: request.append(key_byte) self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response def read_data_by_periodic_identifier(self, transmission_mode, identifier): """ Sends a "read data by periodic identifier" request for 'identifier' :param transmission_mode: Transmission mode :param identifier: Identifier :return: Response data if successful, None otherwise """ if (transmission_mode is None or identifier is None or len(identifier) == 0): return None request = [0] * (2 + len(identifier)) request[0] = ServiceID.READ_DATA_BY_PERIODIC_IDENTIFIER request[1] = transmission_mode for i in range(0, len(identifier)): request[2 + i] = identifier[i] self.tp.send_request(request) response = self.receive_response(self.P3_CLIENT) return response
19,688
32.484694
76
py
caringcaribou
caringcaribou-master/caringcaribou/utils/common.py
def parse_int_dec_or_hex(value): """Parses an integer on base 10 (decimal) or 16 (hex with "0x" prefix) Examples: parse_int_dec_or_hex("1234") -> 1234 parse_int_dec_or_hex("0xa7") -> 167 :param value: the value to parse :type value: str :rtype int """ return int(value, 0) def str_to_int_list(s): """Converts a string representing CAN message data into a list of ints. Example: str_to_int_list("0102c0ffee") -> [01, 02, 0xc0, 0xff, 0xee] :param s: string representation of hex data :type s: str :return: list of byte values representing 's' :rtype: [int] """ return [int(s[i * 2:i * 2 + 2], 16) for i in range(len(s) // 2)] def int_from_byte_list(byte_values, start_index=0, length=None): """Parses a range of unsigned-up-to-8-bit-ints (bytes) from a list into a single int Example: int_from_byte_list([0x11, 0x22, 0x33, 0x44], 1, 2) = 0x2233 = 8755 :param byte_values: list of byte values :param start_index: index of first byte in 'byte_values' to parse :param length: number of bytes to parse (None means "parse all") :type byte_values: [int] :type start_index: int :type length: int :return: int representation of parsed bytes :rtype int """ if length is None: length = len(byte_values) value = 0 for i in (range(start_index, start_index+length)): value = value << 8 value += byte_values[i] return value def list_to_hex_str(data, delimiter=""): """Returns a hex string representation of the int values in 'data', separated with 'delimiter' between each byte Example: list_to_hex_str([10, 100, 200]) -> 0a.64.c8 list_to_hex_str([0x07, 0xff, 0x6c], "") -> 07ff6c :param data: iterable of values :param delimiter: separator between values in output :type data: [int] :type delimiter: str :return: hex string representation of data :rtype str """ data_string = delimiter.join(["{0:02x}".format(i) for i in data]) return data_string def hex_str_to_nibble_list(data): """ Converts a hexadecimal str values into a list of int nibbles. Example: hex_str_to_nibble_list("12ABF7") -> [0x1, 0x2, 0xA, 0xB, 0xF, 0x7] :param data: str of hexadecimal values :type data: str :return: list of int nibbles :rtype [int] """ if data is None: return None data_ints = [] for nibble_str in data: nibble_int = int(nibble_str, 16) data_ints.append(nibble_int) return data_ints def msg_to_candump_format(msg): """Converts a CAN message to a string on candump format :param msg: message to convert :type msg: can.Message :return: candump format representation of 'msg' :rtype str """ if msg.is_extended_id: output = "({0:.6f}) {1} {2:08X}#{3}" else: output = "({0:.6f}) {1} {2:03X}#{3}" data = list_to_hex_str(msg.data, "") candump = output.format(msg.timestamp, msg.channel, msg.arbitration_id, data) return candump
3,067
27.407407
88
py
caringcaribou
caringcaribou-master/caringcaribou/utils/__init__.py
0
0
0
py
resmap
resmap-master/sec_resonance_map.py
import numpy as np import math import sys from numpy import linalg ## MASS OF THE STAR ### # Solar units MC=0.0 ####################### ## USED FOR INTEGRATION CONTROL IN CALC OF BINT ## NSIMP=100 ################################################## ## NOT EVERTHING BELOW IS USED. EXPANSION FOR LATER ## def load_ic(arr,num): ncheck=len(arr) if not ncheck==num+1: print("SERIOUS ERROR IN ICS. ASSERTING.") sys.exit() tmp_arr=np.zeros(num) for ic in xrange(1,num+1): tmp_arr[ic-1]=float(arr[ic]) return tmp_arr def read_input(filename): fhndle=open(filename,"r") num=0 for line in fhndle: if line[0:3]=="NUM": junk,cnum=line.split() num=int(cnum) m=np.zeros(num) a=np.zeros(num) e=np.zeros(num) w=np.zeros(num) I=np.zeros(num) O=np.zeros(num) if num==0:continue item=line.split() if item[0]=="m": m=load_ic(item,num) elif item[0]=="a": a=load_ic(item,num) elif item[0]=="e": e=load_ic(item,num) elif item[0]=="w": w=load_ic(item,num) elif item[0]=="I": I=load_ic(item,num) elif item[0]=="O": O=load_ic(item,num) else: continue fhndle.close() return m,a,e,w,I,O def read_controls(filename): dict={"starting time":0.0, "number of intervals":1, "time interval":100*math.pi*2.0, "radial zones":1000, "inner radius":0.1, "outer radius":30., "include GR":0, "star mass":1.0, "test e":0.0, "test a":0.1, "test I":0.0, "test w":0.0, "test O":0.0} inlist=[] fhndle=open(filename,"r") for invalue in fhndle: k,v=invalue.rstrip().split("=") inlist.append(k) inlist.append(v) fhndle.close() for item in xrange(len(inlist)): if inlist[item] =="starting time" : dict[inlist[item]]=float(inlist[item+1]) elif inlist[item]=="number of intervals" : dict[inlist[item]]=int (inlist[item+1]) elif inlist[item]=="time interval" : dict[inlist[item]]=float(inlist[item+1]) elif inlist[item]=="radial zones" : dict[inlist[item]]=int (inlist[item+1]) elif inlist[item]=="inner radius" : dict[inlist[item]]=float(inlist[item+1]) elif inlist[item]=="outer radius" : dict[inlist[item]]=float(inlist[item+1]) elif inlist[item]=="include GR" : dict[inlist[item]]=int (inlist[item+1]) elif inlist[item]=="star mass" : dict[inlist[item]]=float(inlist[item+1]) elif inlist[item]=="test e" : dict[inlist[item]]=float(inlist[item+1]) elif inlist[item]=="test a" : dict[inlist[item]]=float(inlist[item+1]) elif inlist[item]=="test I" : dict[inlist[item]]=float(inlist[item+1]) elif inlist[item]=="test w" : dict[inlist[item]]=float(inlist[item+1]) elif inlist[item]=="test O" : dict[inlist[item]]=float(inlist[item+1]) return dict def nmm(a,m): return math.sqrt( (m+MC)/a**3 ) def simpson(y0,y1,y2,h): a=y0 b=(3.*(y2-a)-4.*(y2-y1))/h c=((y2-a)/h-b)/h return h*(a+h*(0.5*b+h*c/3.)) def laplace_integrand(j,s,a,phi): return math.cos(j*phi)/((1.-2.*a*math.cos(phi)+a*a)**s) def bint(j,s,a): dphi=2.0*math.pi/float(NSIMP) val=0.0 for i in xrange(NSIMP): phi0=i*dphi phi1=phi0+0.5*dphi phi2=phi0+dphi y0=laplace_integrand(j,s,a,phi0) y1=laplace_integrand(j,s,a,phi1) y2=laplace_integrand(j,s,a,phi2) val+=simpson(y0,y1,y2,dphi) return val/math.pi def ajk(a,b): if a>b: return b/a else: return a/b def ajkbar(a,b): if a>b: return 1.0 else: return a/b def AijBij(m,a,n): N=len(m) A=np.zeros((N,N)) B=np.zeros((N,N)) # yeah, the following ain't pretty. I'll fix this when speed is needed. for i in xrange(N): for k in xrange(i): factor=0.25*n[i]*(m[k]/(MC+m[i]))*ajk(a[i],a[k])*ajkbar(a[i],a[k]) b1=bint(1.,1.5,ajk(a[i],a[k])) b2=bint(2.,1.5,ajk(a[i],a[k])) A[i][i]+=factor*b1 A[i][k]=-factor*b2 # A[i][i]+=0.25*n[i]*(m[k]/(MC+m[i]))*ajk(a[i],a[k])*ajkbar(a[i],a[k])*bint(1.,1.5,ajk(a[i],a[k])) # A[i][k]=-0.25*n[i]*(m[k]/(MC+m[i]))*ajk(a[i],a[k])*ajkbar(a[i],a[k])*bint(2.,1.5,ajk(a[i],a[k])) B[i][i]-=factor*b1 B[i][k]=+factor*b1 # B[i][i]-=0.25*n[i]*(m[k]/(MC+m[i]))*ajk(a[i],a[k])*ajkbar(a[i],a[k])*bint(1.,1.5,ajk(a[i],a[k])) # B[i][k]=+0.25*n[i]*(m[k]/(MC+m[i]))*ajk(a[i],a[k])*ajkbar(a[i],a[k])*bint(1.,1.5,ajk(a[i],a[k])) for k in xrange(i+1,N): factor=0.25*n[i]*(m[k]/(MC+m[i]))*ajk(a[i],a[k])*ajkbar(a[i],a[k]) b1=bint(1.,1.5,ajk(a[i],a[k])) b2=bint(2.,1.5,ajk(a[i],a[k])) A[i][i]+=factor*b1 A[i][k]=-factor*b2 B[i][i]-=factor*b1 B[i][k]=+factor*b1 return A,B def AB_part(m,a,apart,npart): N=len(m) A=0. B=0. for k in xrange(N): A+=0.25*npart*m[k]/(MC)*ajk(apart,a[k])*ajkbar(apart,a[k])*bint(1.,1.5,ajk(apart,a[k])) B=-1.0*A return A,B def AjBj_part(m,a,apart,npart): N=len(m) A=np.zeros(N) B=np.zeros(N) for k in xrange(N): factor=0.25*npart*m[k]/(MC)*ajk(apart,a[k])*ajkbar(apart,a[k]) A[k]=-factor*bint(2.,1.5,ajk(apart,a[k])) B[k]=+factor*bint(1.,1.5,ajk(apart,a[k])) return A,B def dRdk(i,A,h,k): N=len(h) val=A[i][i]*k[i] for l in xrange(i): val+=A[i][l]*k[l] for l in xrange(i+1,N): val+=A[i][l]*k[l] return val def dRdh(i,A,h,k): N=len(h) val=A[i][i]*h[i] for l in xrange(i): val+=A[i][l]*h[l] for l in xrange(i+1,N): val+=A[i][l]*h[l] return val def dRdp(i,B,p,q): N=len(p) val=B[i][i]*p[i] for l in xrange(i): val+=B[i][l]*p[l] for l in xrange(i+1,N): val+=B[i][l]*p[l] return val def dRdq(i,B,p,q): N=len(q) val=B[i][i]*q[i] for l in xrange(i): val+=B[i][l]*q[l] for l in xrange(i+1,N): val+=B[i][l]*q[l] return val def hdot(i,A,h,k): return dRdk(i,A,h,k) def kdot(i,A,h,k): return -dRdh(i,A,h,k) def pdot(i,B,p,q): return dRdq(i,B,p,q) def qdot(i,B,p,q): return -dRdp(i,B,p,q) def set_hk(e,w): N=len(e) h=np.zeros(N) k=np.zeros(N) for i in xrange(N): h[i]=e[i]*math.sin(w[i]) for i in xrange(N): k[i]=e[i]*math.cos(w[i]) return h,k def set_pq(I,O): N=len(I) p=np.zeros(N) q=np.zeros(N) for i in xrange(N): p[i]=I[i]*math.sin(O[i]) for i in xrange(N): q[i]=I[i]*math.cos(O[i]) return p,q def get_ew(h,k): N=len(h) e=np.zeros(N) w=np.zeros(N) for i in xrange(N): w[i]=math.atan2(h[i],k[i]) if w[i]<0.0:w[i]+=math.pi*2.0 sinw=math.sin(w[i]) if sinw>0.1 or sinw < -0.1:e[i]=h[i]/sinw else: e[i]=k[i]/math.cos(w[i]) return e,w def get_IO(p,q): N=len(p) I=np.zeros(N) O=np.zeros(N) for i in xrange(N): O[i]=math.atan2(p[i],q[i]) if O[i]<0.0:O[i]+=math.pi*2.0 sinO=math.sin(O[i]) if sinO>0.1 or sinO < -0.1:I[i]=p[i]/sinO else: I[i]=q[i]/math.cos(O[i]) return I,O def hkdots_GR(h,k,a,n): N=len(h) hdotgr=np.zeros(N) kdotgr=np.zeros(N) c=10070.0 wgrfac=3.*MC/c**2 for i in xrange(N): wgr=wgrfac*n[i]/a[i] hdotgr[i]= k[i]*wgr kdotgr[i]=-h[i]*wgr return hdotgr,kdotgr def main(): if not len(sys.argv)==3: print("\nUSAGE:") print("python ./sec_resonance_map.py input_file param_file\n") print("Please give input file for initial conditions and parameter file for script control.\n") sys.exit() mIC,aIC,eIC,wIC,IIC,OIC=read_input(sys.argv[1]) global MC dict=read_controls(sys.argv[2]) T0=dict["starting time"] NTIME=dict["number of intervals"] DTIME=dict["time interval"] NR=dict["radial zones"] RIN=dict["inner radius"] ROUT=dict["outer radius"] INCLUDEGR=dict["include GR"] MC=dict["star mass"] etest_part=dict["test e"] atest_part=dict["test a"] itest_part=dict["test I"] wtest_part=dict["test w"] otest_part=dict["test O"] mtest_part=0.0 ### INITIALIZE ARRAYS ## N=len(mIC) m=np.zeros(N) a=np.zeros(N) e=np.zeros(N) I=np.zeros(N) w=np.zeros(N) O=np.zeros(N) n=np.zeros(N) twopi=2.0*math.pi ####################### ## RADIANS #################### for i in xrange(N): m[i]=mIC[i] a[i]=aIC[i] e[i]=eIC[i] I[i]=IIC[i]*math.pi/180. O[i]=OIC[i]*math.pi/180. w[i]=wIC[i]*math.pi/180. n[i]=nmm(a[i],m[i]) ############################### h,k=set_hk(e,w) p,q=set_pq(I,O) ### As and Bs ############################### # Get A and B MATRICES AND EIGENVALUES A,B=AijBij(m,a,n) lA,vA = linalg.eig(A) lB,vB = linalg.eig(B) ############################################# ## CALCULATE SECULAR THEORY!!! ############## #print "#A ",A*2.*180. #print "#B ",B*2.*180. #print "#lA ",lA*2.*180. #print "#lB ",lB*2.*180. #print "vA ",vA #print "vB ",vB #print "h ",h #print "k ",k #print "p ",p #print "q ",q vAinv = linalg.inv(vA) vBinv = linalg.inv(vB) ssinb = vAinv.dot(h) scosb = vAinv.dot(k) tsing = vBinv.dot(p) tcosg = vBinv.dot(q) #print "SSINB ",ssinb #print "SCOSB ",scosb eBeta=np.zeros(N) eScale=np.zeros(N) iBeta=np.zeros(N) iScale=np.zeros(N) for i in xrange(N): eBeta[i]=math.atan2(ssinb[i],scosb[i]) iBeta[i]=math.atan2(tsing[i],tcosg[i]) sb=math.sin(eBeta[i]) if sb == 0.0: eScale[i]=scosb[i]/math.cos(eBeta[i]) else: eScale[i]=ssinb[i]/sb sb=math.sin(iBeta[i]) if sb == 0.0: iScale[i]=tcosg[i]/math.cos(iBeta[i]) else: iScale[i]=tsing[i]/sb #print "#eScale,eBeta ",eScale,eBeta*180./math.pi #print "#iScale,iBeta ",iScale,iBeta*180./math.pi ee = np.zeros((N,N)) ii = np.zeros((N,N)) for i in xrange(N): for j in xrange(N): ee[i][j]=eScale[j]*vA[i][j] ii[i][j]=iScale[j]*vB[i][j] #print " ee ",i,j,ee[i][j] ## NOW WE HAVE THE SECULAR THEORY. INTRODUCE TEST PARTICLE AT RANGE OF RADII ### ## RADIAL RANGE ############################## ## ## PRINT HEADER print "# FOR TEST PARTICLE" print "# index, radius (AU), A (deg/yr), B (deg/yr), eforced, Iforced (deg), A eigenvalues (deg/yr) and B eigenvalues (deg/yr)" ## ## for ir in xrange(NR): rad = RIN + (ROUT-RIN)*float(ir)/float(NR) for i in [N-1]: apart=rad*1.0 npart=nmm(apart,mtest_part) ############################################## Apart,Bpart=AB_part(m,a,apart,npart) Aj,Bj=AjBj_part(m,a,apart,npart) # TEST PARTICLE A,B,Aj,Bj nu = np.zeros(N) mu = np.zeros(N) for i in xrange(N): for j in xrange(N): nu[i]+=Aj[j]*ee[j][i] mu[i]+=Bj[j]*ii[j][i] eforced=0. iforced=0. for itime in xrange(NTIME): time = T0 +itime*DTIME h0=0.0 k0=0.0 p0=0.0 q0=0.0 for i in xrange(N): h0+= -nu[i]/(Apart-lA[i])*math.sin(lA[i]*time+eBeta[i]) k0+= -nu[i]/(Apart-lA[i])*math.cos(lA[i]*time+eBeta[i]) p0+= -mu[i]/(Bpart-lB[i])*math.sin(lB[i]*time+iBeta[i]) q0+= -mu[i]/(Bpart-lB[i])*math.cos(lB[i]*time+iBeta[i]) eforced+=math.sqrt(h0**2+k0**2) iforced+=math.sqrt(p0**2+q0**2) eforced/=float(NTIME) iforced/=float(NTIME) ### OUTPUT!!!! #print "# FOR TEST PARTICLE" #print "# index, radius (AU), A (deg/yr), B (deg/yr), eforced, Iforced (deg), A eigenvalues (deg/yr) and B eigenvalues (deg/yr)" print ir,rad,Apart*2.*180.,Bpart*2.*180.,eforced,iforced, for i in xrange(N):print lA[i]*2.*180., for i in xrange(N):print lB[i]*2.*180., print "" ############################################################################################################# main()
12,048
26.015695
133
py
GPTScore
GPTScore-main/utils.py
import os import pickle import sys import nltk from mosestokenizer import * from nltk import word_tokenize from nltk.tokenize import sent_tokenize import json nltk.download('stopwords') detokenizer = MosesDetokenizer('en') def read_demos(json_path): asp_demos = json.load(open(json_path)) asp_dfs, demos = asp_demos["asp_definition"], asp_demos["demo"] return demos, asp_dfs def lower_check(text): # The BAGEL dataset uses X to replace named entities. if text.startswith("X ") == False: text1 = text[0].lower() + text[1:] else: text1 = text return text1 def add_dot(text): if text.strip()[-1] != '.': text = text.strip() + ' .' new_text = text return new_text def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') def read_pickle(file): with open(file, 'rb') as f: data = pickle.load(f) return data def save_pickle(data, file): with open(file, 'wb') as f: pickle.dump(data, f) print(f'Saved to {file}.') def detokenize(text: str): words = text.split(" ") return detokenizer(words) # Restore print def enablePrint(): sys.stdout = sys.__stdout__
1,354
20.854839
67
py
GPTScore
GPTScore-main/score_d2t.py
import argparse import os import time import numpy as np from utils import * from gpt3_score import gpt3score from transformers import GPT2Tokenizer import json class Scorer: """ Support GPT3-based (davinci, curie, babbage, ada), OPT-based, GPT2-based, FLAN-T5-based (19 models) """ def __init__(self, args=None): self.args = args self.device = self.args.device self.eval_asp = self.args.aspect self.data = read_pickle(self.args.file_path) self.demos, self.asp_dfs = read_demos(self.args.demo_path) # Evaluate a small dataset first.. print('Since GPT3-based models are expensive, we can test them on a small number of samples first.') print('The default number of test samples is 2.') import random random.seed(2) N = 2 idxs = random.sample(range(0, len(self.data) - 1), N) new_data = {idx: self.data[idx] for idx in idxs} self.data = new_data print('the num of evaluation samples: ', len(self.data)) def save_data(self, path): save_pickle(self.data, path) def demo_convert(self, demos, template): refhyp_demos = [] hypref_demos = [] for demo in demos: src_line = demo["src"].strip() ref_line = demo["ref_summ"].strip() hyp_line = demo["sys_summ"].strip() polar = demo["polarity"].strip() refhyp_demo = template.replace("XXXXX", ref_line).replace("YYYYY", hyp_line) refhyp_demos.append(refhyp_demo) hypref_demo = template.replace("XXXXX", hyp_line).replace("YYYYY",ref_line) hypref_demos.append(hypref_demo) return refhyp_demos, hypref_demos def score(self, metrics): """ metrics: list of metrics """ for metric_name in metrics: if metric_name in [ "opt125m_score", "opt350m_score", "opt1_3B_score", "opt2_7B_score", "opt6_7B_score", "opt13B_score", "opt30B_score", "opt66B_score", "gpt2_medium_score", "gpt2_large_score", "gpt2_xl_score", "gptJ6B_score" ]: """ Vanilla OPT and GPT2 models""" from opt_score import OPTScorer eval_asps = ["informativeness", "naturalness", "quality"] metric2checkpoint = { "opt125m_score": "facebook/opt-125m", "opt350m_score": "facebook/opt-350m", "opt1_3B_score": "facebook/opt-1.3b", "opt2_7B_score": "facebook/opt-2.7b", "opt6_7B_score": "facebook/opt-6.7b", "opt13B_score": "facebook/opt-13b", "opt66B_score": "facebook/opt-66b", "gpt2_medium_score": "gpt2-medium", "gpt2_large_score": "gpt2-large", "gpt2_xl_score": "gpt2-xl", "gptJ6B_score": "EleutherAI/gpt-j-6B", } print('metric_name: ', metric_name) checkpoint = metric2checkpoint[metric_name] opt_scorer = OPTScorer(device=self.device, checkpoint=checkpoint) print(f'OPTScore setup finished. Begin calculating OPTScore.') start = time.time() for e_asp in eval_asps: print('num of examples: ', len(self.data)) demo = self.demos[e_asp] asp_df = self.asp_dfs[e_asp] asp_df = asp_df.strip().replace(':', '. ') print('demo: ', demo) print('asp_df: ', asp_df) refhyp_templates = ["XXXXX In other words , YYYYY", " In other words , "] template = refhyp_templates[0] # template refhyp_demos, hypref_demos = self.demo_convert(demo, template) for doc_id in self.data: print('doc_id: ', doc_id) ref_summs = self.data[doc_id]['ref_summs'] ref_summs = [add_dot(detokenize(line)) for line in ref_summs] # avg, num_ref_summs: 127.65257142857143 sys_summ = add_dot(detokenize(self.data[doc_id]['sys_summ'])) ## ref->hypo # define the prefix text... if self.args.use_ist and self.args.use_demo: refhyp_demos_str = "\n".join(refhyp_demos) prefix = asp_df + '\n' + refhyp_demos_str + '\n' elif self.args.use_ist and not self.args.use_demo: prefix = asp_df + '\n' elif not self.args.use_ist and not self.args.use_demo: prefix = '' # ref_summs1 = [prefix + template.replace('XXXXX', line).replace('YYYYY', '') for line in ref_summs] ref_summs1 = [prefix + line for line in ref_summs] ref_hypo_scores = np.array(opt_scorer.score(ref_summs1, [sys_summ] * len(ref_summs), prompt_text=refhyp_templates[1], batch_size=1)) ## hypo->ref # define the prefix text... if self.args.use_ist and self.args.use_demo: hypref_demos_str = "\n".join(hypref_demos) prefix = asp_df + '\n' + refhyp_demos_str + '\n' elif self.args.use_ist and not self.args.use_demo: prefix = asp_df + '\n' elif not self.args.use_ist and not self.args.use_demo: prefix = '' sys_summ1 = [sys_summ] * len(ref_summs) # sys_summ1 = [prefix + template.replace('XXXXX', line).replace('YYYYY', '') for line in sys_summ1] sys_summ1 = [prefix + line for line in sys_summ1] hypo_ref_scores = np.array(opt_scorer.score(sys_summ1, ref_summs, prompt_text=refhyp_templates[1],batch_size=1)) ref_hypo = ref_hypo_scores.max() hypo_ref = hypo_ref_scores.max() avg_f = (0.5 * (ref_hypo_scores + hypo_ref_scores)).max() harm_f = (ref_hypo_scores * hypo_ref_scores / (ref_hypo_scores + hypo_ref_scores)).max() print('ref_hypo: ', ref_hypo) print('hypo_ref: ', hypo_ref) print('avg_f: ', avg_f) print('harm_f: ', harm_f) if self.args.use_ist: self.data[doc_id]['scores'][f'{metric_name}_{e_asp}_ref_hypo'] = ref_hypo self.data[doc_id]['scores'][f'{metric_name}_{e_asp}_hypo_ref'] = hypo_ref self.data[doc_id]['scores'][f'{metric_name}_{e_asp}_avg_f'] = avg_f self.data[doc_id]['scores'][f'{metric_name}_{e_asp}_harm_f'] = harm_f else: self.data[doc_id]['scores'][f'{metric_name}_ref_hypo'] = ref_hypo self.data[doc_id]['scores'][f'{metric_name}_hypo_ref'] = hypo_ref self.data[doc_id]['scores'][f'{metric_name}_avg_f'] = avg_f self.data[doc_id]['scores'][f'{metric_name}_harm_f'] = harm_f print(f'Finished calculating OPTScore, time passed {time.time() - start}s.') opt_scorer = None elif metric_name in ["flan_small_score", "flan_base_score", "flan_large_score","flan_xl_score", "flan_xxl_score"]: """ Vanilla flan_small, flan_base, flan_large, flan_xl, flan_xxl """ from flan_score import FLANScorer eval_asps = ["informativeness", "naturalness", "quality"] metric2checkpoint = { "flan_small_score": "google/flan-t5-small", "flan_base_score": "google/flan-t5-base", "flan_large_score": "google/flan-t5-large", "flan_xl_score": "google/flan-t5-xl", "flan_xxl_score": "google/flan-t5-xxl", } print('metric_name: ', metric_name) checkpoint = metric2checkpoint[metric_name] flan_scorer = FLANScorer(device=self.device, checkpoint=checkpoint) print(f'FLANScorer setup finished. Begin calculating FLANScorer.') start = time.time() for e_asp in eval_asps: # Evaluation is cheap when using non-GPT3 models, so here, we evaluate all aspects by default. print('num of examples: ', len(self.data)) demo = self.demos[e_asp] asp_df = self.asp_dfs[e_asp] asp_df = asp_df.strip().replace(':', '. ') print('demo: ', demo) print('asp_df: ', asp_df) refhyp_templates = ["XXXXX In other words , YYYYY", ] template = refhyp_templates[0] # template refhyp_demos, hypref_demos = self.demo_convert(demo, template) for doc_id in self.data: print('doc_id: ', doc_id) ref_summs = self.data[doc_id]['ref_summs'] ref_summs = [add_dot(detokenize(line)) for line in ref_summs] # avg, num_ref_summs: 127.65257142857143 sys_summ = add_dot(detokenize(self.data[doc_id]['sys_summ'])) ## ref->hypo # define the prefix text... if self.args.use_ist and self.args.use_demo: refhyp_demos_str = "\n".join(refhyp_demos) prefix = asp_df + '\n' + refhyp_demos_str + '\n' elif self.args.use_ist and not self.args.use_demo: prefix = asp_df + '\n' elif not self.args.use_ist and not self.args.use_demo: prefix = '' ref_summs1 = [prefix + template.replace('XXXXX', line).replace('YYYYY', '') for line in ref_summs] ref_hypo_scores = np.array(flan_scorer.score(ref_summs1, [sys_summ] * len(ref_summs), batch_size=1)) ## hypo->ref # define the prefix text... if self.args.use_ist and self.args.use_demo: hypref_demos_str = "\n".join(hypref_demos) prefix = asp_df + '\n' + refhyp_demos_str + '\n' elif self.args.use_ist and not self.args.use_demo: prefix = asp_df + '\n' elif not self.args.use_ist and not self.args.use_demo: prefix = '' sys_summ1 = [sys_summ] * len(ref_summs) sys_summ1 = [prefix + template.replace('XXXXX', line).replace('YYYYY', '') for line in sys_summ1] hypo_ref_scores = np.array(flan_scorer.score(sys_summ1, ref_summs, batch_size=1)) ref_hypo = ref_hypo_scores.max() hypo_ref = hypo_ref_scores.max() avg_f = (0.5 * (ref_hypo_scores + hypo_ref_scores)).max() harm_f = (ref_hypo_scores * hypo_ref_scores / (ref_hypo_scores + hypo_ref_scores)).max() print('ref_hypo: ', ref_hypo) print('hypo_ref: ', hypo_ref) print('avg_f: ', avg_f) print('harm_f: ', harm_f) if self.args.use_ist: self.data[doc_id]['scores'][f'{metric_name}_{e_asp}_ref_hypo'] = ref_hypo self.data[doc_id]['scores'][f'{metric_name}_{e_asp}_hypo_ref'] = hypo_ref self.data[doc_id]['scores'][f'{metric_name}_{e_asp}_avg_f'] = avg_f self.data[doc_id]['scores'][f'{metric_name}_{e_asp}_harm_f'] = harm_f else: self.data[doc_id]['scores'][f'{metric_name}_ref_hypo'] = ref_hypo self.data[doc_id]['scores'][f'{metric_name}_hypo_ref'] = hypo_ref self.data[doc_id]['scores'][f'{metric_name}_avg_f'] = avg_f self.data[doc_id]['scores'][f'{metric_name}_harm_f'] = harm_f print(f'Finished calculating FLANScorer, time passed {time.time() - start}s.') flan_scorer = None elif metric_name == 'gpt3_score': print(f'Perform the gpt3_score...') start = time.time() print('num of examples: ', len(self.data)) demo = self.demos[self.eval_asp] asp_df = self.asp_dfs[self.eval_asp] print('demo: ', demo) print('asp_df: ', asp_df) refhyp_templates = ["XXXXX In other words , \nYYYYY",] template = refhyp_templates[0] # template refhyp_demos, hypref_demos = self.demo_convert(demo, template) for samp_id, doc_id in enumerate(self.data): print('samp_id: ', samp_id) ref_summs = self.data[doc_id]['ref_summs'] ref_summs = [detokenize(line) for line in ref_summs] sys_summ = detokenize(self.data[doc_id]['sys_summ']) ref_hypo_scores = [] hypo_ref_scores = [] keep_seen_refsumm_score = {} for k, ref_summ in enumerate(ref_summs): print() print('aspect: %s; samp_id: %d; ref_summ_id/total_ref_summ: %d/%d' % ( self.eval_asp, samp_id, k, len(ref_summs))) # Add a period if missing punctuation at the end of the sentence. ref_summ = add_dot(ref_summ) sys_summ = add_dot(sys_summ) if ref_summ in keep_seen_refsumm_score: # skip the duplicate ref_summ ref_hypo_score = keep_seen_refsumm_score[ref_summ][0] hypo_ref_score = keep_seen_refsumm_score[ref_summ][1] ref_hypo_scores.append(ref_hypo_score) hypo_ref_scores.append(hypo_ref_score) else: ## ref->hypo # define the prefix text... if self.args.use_ist and self.args.use_demo: refhyp_demos_str = "\n\n".join(refhyp_demos) prefix = asp_df + '\n\n' + refhyp_demos_str + '\n\n' elif self.args.use_ist and not self.args.use_demo: prefix = asp_df + '\n' elif not self.args.use_ist and not self.args.use_demo: prefix = '' input1 = template.replace("XXXXX", ref_summ).replace("YYYYY", "") input1 = prefix + input1 output1 = lower_check(sys_summ) ref_hypo_score = gpt3score(input1, output1, self.args.gpt3model, self.args.api_key) ref_hypo_scores.append(ref_hypo_score) ## hypo->ref # define the prefix text... if self.args.use_ist and self.args.use_demo: hypref_demos_str = "\n\n".join(hypref_demos) prefix = asp_df + '\n\n' + hypref_demos_str + '\n\n' elif self.args.use_ist and not self.args.use_demo: prefix = asp_df + '\n' elif not self.args.use_ist and not self.args.use_demo: prefix = '' input2 = template.replace("XXXXX", sys_summ).replace("YYYYY", "") input2 = prefix + input2 output2 = lower_check(ref_summ) hypo_ref_score = gpt3score(input2, output2, self.args.gpt3model, self.args.api_key) hypo_ref_scores.append(hypo_ref_score) keep_seen_refsumm_score[ref_summ] =[ref_hypo_score,hypo_ref_score] print('keep_seen_refsumm_score: ',keep_seen_refsumm_score) print('len(ref_hypo_scores): ', len(ref_hypo_scores)) print('len(hypo_ref_scores): ', len(hypo_ref_scores)) ref_hypo_scores = np.array(ref_hypo_scores) hypo_ref_scores = np.array(hypo_ref_scores) ref_hypo = ref_hypo_scores.max() hypo_ref = hypo_ref_scores.max() avg_f = (0.5 * (ref_hypo_scores + hypo_ref_scores)).max() harm_f = (ref_hypo_scores * hypo_ref_scores / (ref_hypo_scores + hypo_ref_scores)).max() print('ref_hypo: ', ref_hypo) print('hypo_ref: ', hypo_ref) print('avg_f: ', avg_f) print('harm_f: ', harm_f) if self.args.use_ist: self.data[doc_id]['scores'][f'{metric_name}_{self.eval_asp}_ref_hypo'] = ref_hypo self.data[doc_id]['scores'][f'{metric_name}_{self.eval_asp}_hypo_ref'] = hypo_ref self.data[doc_id]['scores'][f'{metric_name}_{self.eval_asp}_avg_f'] = avg_f self.data[doc_id]['scores'][f'{metric_name}_{self.eval_asp}_harm_f'] = harm_f else: self.data[doc_id]['scores'][f'{metric_name}_ref_hypo'] = ref_hypo self.data[doc_id]['scores'][f'{metric_name}_hypo_ref'] = hypo_ref self.data[doc_id]['scores'][f'{metric_name}_avg_f'] = avg_f self.data[doc_id]['scores'][f'{metric_name}_harm_f'] = harm_f print(f'Finished calculating gpt3_score, time passed {time.time() - start}s.') else: raise NotImplementedError def main(): parser = argparse.ArgumentParser(description='Scorer parameters') parser.add_argument('--file_path', type=str, default='XXX', help='The data to load from.') parser.add_argument('--demo_path', type=str, default='XXX', help='The demonstrated samples to load from.') parser.add_argument('--device', type=str, default='cuda:0', help='The device to run on.') parser.add_argument('--dataname', type=str, default='BAGEL', required=False, help='The name of the evaluated dataset.') parser.add_argument('--aspect', type=str, default='Engaging', required=False, help='The evaluated aspect considered.') parser.add_argument('--gpt3model', type=str, default='ada', required=False, help='Set which GPT3-based model to use.') parser.add_argument('--api_key', type=str, default='YOUR_OPENAI_API_KEY', required=False, help='The OPENAI API key.') parser.add_argument('--use_ist', type=str2bool, default=False, required=True, help='If set to True, use instruction.') parser.add_argument('--use_demo', type=str2bool, default=False, required=False, help='If set to True, use demonstrated samples.') parser.add_argument('--output', type=str, default="XXXX", help='The output path to save the calculated scores.') parser.add_argument('--out_dir_name', type=str, default="XXXX", required=False, help='The output folder name to save the calculated scores.') parser.add_argument('--gpt3_score', type=str2bool, default=False, help='Whether to calculate gpt3_score.') parser.add_argument('--opt125m_score', type=str2bool, default=False, help='Whether to calculate facebook/opt-125m.') parser.add_argument('--opt350m_score', type=str2bool, default=False, help='Whether to calculate facebook/opt-350m.') parser.add_argument('--opt1_3B_score', type=str2bool, default=False, help='Whether to calculate facebook/opt-1.3b.') parser.add_argument('--opt2_7B_score', type=str2bool, default=False, help='Whether to calculate opt2_7B_score.') parser.add_argument('--opt6_7B_score', type=str2bool, default=False, help='Whether to calculate opt6_7B_score.') parser.add_argument('--opt13B_score', type=str2bool, default=False, help='Whether to calculate opt13B_score.') parser.add_argument('--opt66B_score', type=str2bool, default=False, help='Whether to calculate opt66B_score.') parser.add_argument('--gpt2_medium_score', type=str2bool, default=False, help='Whether to calculate gpt2_medium_score.') parser.add_argument('--gpt2_large_score', type=str2bool, default=False, help='Whether to calculate gpt2_large_score.') parser.add_argument('--gpt2_xl_score', type=str2bool, default=False, help='Whether to calculate gpt2_xl_score.') parser.add_argument('--gptJ6B_score', type=str2bool, default=False, help='Whether to calculate gptJ6B_score.') parser.add_argument('--flan_small_score', type=str2bool, default=False, help='Whether to calculate flan_small_score.') parser.add_argument('--flan_base_score', type=str2bool, default=False, help='Whether to calculate flan_base_score.') parser.add_argument('--flan_large_score', type=str2bool, default=False, help='Whether to calculate flan_large_score.') parser.add_argument('--flan_xl_score', type=str2bool, default=False, help='Whether to calculate flan_xl_score.') parser.add_argument('--flan_xxl_score', type=str2bool, default=False, help='Whether to calculate flan_xxl_score.') args = parser.parse_args() METRICS = [] if args.gpt3_score: METRICS.append('gpt3_score') if args.opt350m_score: METRICS.append('opt350m_score') if args.opt1_3B_score: METRICS.append('opt1_3B_score') if args.opt6_7B_score: METRICS.append('opt6_7B_score') if args.opt13B_score: METRICS.append('opt13B_score') if args.opt66B_score: METRICS.append('opt66B_score') if args.flan_small_score: METRICS.append('flan_small_score') if args.flan_base_score: METRICS.append('flan_base_score') if args.flan_large_score: METRICS.append('flan_large_score') if args.flan_xl_score: METRICS.append('flan_xl_score') if args.flan_xxl_score: METRICS.append('flan_xxl_score') if args.gpt2_medium_score: METRICS.append('gpt2_medium_score') if args.gpt2_large_score: METRICS.append('gpt2_large_score') if args.gpt2_xl_score: METRICS.append('gpt2_xl_score') if args.gptJ6B_score: METRICS.append('gptJ6B_score') print('METRICS: ',METRICS) out_dir1 = args.out_dir_name data_dir = "./datas/meta_datas/d2t/" demon_dir = "./datas/demos/d2t/" out_dir = './analysis/d2t/'+out_dir1 if not os.path.exists(out_dir): os.makedirs(out_dir) data_name = args.dataname print('##### eval data_name: ', data_name) print() file_path = data_dir + data_name+'/data.pkl' args.file_path = file_path args.demo_path =demon_dir + data_name + '_demos.json' print('\n'.join(f'{k}={v}' for k, v in vars(args).items())) # args.output = out_dir + '/' + data_name + '_15plainBaseline_score.pkl' args.output = out_dir + '/' + data_name + args.out_dir_name + '_usedemo[' + str(args.use_demo) + ']' + '_useist[' + str(args.use_ist) + ']_OptFlanGpt2_score.pkl' # args.output = out_dir + '/' + data_name + '_' + args.aspect + '_' + args.out_dir_name + '_usedemo[' + str(args.use_demo) + ']' + '_useist[' + str(args.use_ist) + ']_' + args.gpt3model + '.pkl' print('args.output: ', args.output) scorer = Scorer(args) scorer.score(METRICS) scorer.save_data(args.output) if __name__ == '__main__': main()
24,959
53.857143
198
py
GPTScore
GPTScore-main/gpt3_score.py
from gpt_inference import GPT3Model def gpt3score(input, output,gpt3model=None,api_key=None): gpt3model_name = '' if gpt3model == 'ada': gpt3model_name = "text-ada-001" elif gpt3model == 'babbage': gpt3model_name = "text-babbage-001" elif gpt3model == 'curie': gpt3model_name = "text-curie-001" elif gpt3model == 'davinci001': gpt3model_name = "text-davinci-001" elif gpt3model == 'davinci003': gpt3model_name = "text-davinci-003" print('gpt3model_name: ', gpt3model_name) # "text-curie-001", "text-ada-001", "text-babbage-001", "text-davinci-001", "text-davinci-003", metaicl_model = GPT3Model(gpt3model_name, api_key) avg_loss = metaicl_model.do_inference(input, output) score = -avg_loss return score
793
36.809524
99
py
GPTScore
GPTScore-main/gpt_inference.py
import time import sys from transformers import GPT2Tokenizer import openai class GPT3Model(object): def __init__(self, model_name, api_key, logger=None): self.model_name = model_name try: openai.api_key = api_key except Exception: pass self.tokenizer = GPT2Tokenizer.from_pretrained("gpt2-xl") self.logger=logger def do_inference(self, input, output, max_length=2048): losses = [] data = input + output response = self.gpt3(data) out = response["choices"][0] assert input + output == out["text"] i = 0 # find the end position of the input... i = out['logprobs']['text_offset'].index(len(input) - 1) if i == 0: i = i + 1 print('eval text', out['logprobs']['tokens'][i: -1]) loss = -sum(out['logprobs']["token_logprobs"][i:-1]) # ignore the last '.' avg_loss = loss / (len(out['logprobs']['text_offset']) - i-1) # 1 is the last '.' print('avg_loss: ', avg_loss) losses.append(avg_loss) return avg_loss def gpt3(self, prompt, max_len=0, temp=0, num_log_probs=0, echo=True, n=None): response = None received = False while not received: try: response = openai.Completion.create(engine=self.model_name, prompt=prompt, max_tokens=max_len, temperature=temp, logprobs=num_log_probs, echo=echo, stop='\n', n=n) print('prompt: ',prompt) received = True except: error = sys.exc_info()[0] if error == openai.error.InvalidRequestError: # something is wrong: e.g. prompt too long print(f"InvalidRequestError\nPrompt passed in:\n\n{prompt}\n\n") assert False print("API error:", error) time.sleep(1) return response
2,311
34.569231
89
py
GPTScore
GPTScore-main/opt_score.py
# %% import torch import torch.nn as nn import traceback from transformers import BartTokenizer, BartForConditionalGeneration from transformers import GPT2Tokenizer, OPTForCausalLM, GPT2LMHeadModel, GPTJForCausalLM class OPTScorer: def __init__(self, device='cuda:0', max_length=1024, checkpoint=None): # Set up model self.device = device if 'gpt2' in checkpoint: print('gpt2 model') self.tokenizer = GPT2Tokenizer.from_pretrained(checkpoint) self.model = GPT2LMHeadModel.from_pretrained(checkpoint).to(self.device) max_length = 1000 elif 'gpt-j' in checkpoint: print('gpt-j model') self.tokenizer = GPT2Tokenizer.from_pretrained(checkpoint) self.model = GPTJForCausalLM.from_pretrained(checkpoint).to(self.device) max_length = 2000 else: self.tokenizer = GPT2Tokenizer.from_pretrained(checkpoint) self.model = OPTForCausalLM.from_pretrained(checkpoint).to(self.device) max_length = 2000 self.max_length = max_length print('max_length: ', max_length) self.model.eval() def score(self, srcs, tgts, prompt_text, batch_size): """ Score a batch of examples """ def trunk_input(inputs, outputs, reduce_seq, max_length): input_ids = self.tokenizer.encode(inputs)[1:-1] output_ids = self.tokenizer.encode(outputs)[1:-1] reduce_seq_ids = self.tokenizer.encode(reduce_seq)[1:-1] total_len = len(input_ids) + len(output_ids) if total_len > max_length: del_len = len(input_ids) + len(output_ids) - max_length reduce_seq_ids = reduce_seq_ids[:len(reduce_seq_ids) - del_len] reduce_seq = self.tokenizer.decode(reduce_seq_ids[1:-1]) return reduce_seq score_list = [] for i,(src, tgt) in enumerate(zip(srcs, tgts)): print('process:'+str(i) + '/'+str(len(srcs)) ) new_src = trunk_input(src, tgt, src, max_length=self.max_length) src = new_src text = src + prompt_text + tgt if i <1: print('text: ', text) print('tgt: ', tgt) input_ids = self.tokenizer.encode(text) tgt_ids = self.tokenizer.encode(tgt)[1:] output_ids = [-100] * len(input_ids) output_ids[len(input_ids) - len(tgt_ids):] = tgt_ids input_ids = torch.LongTensor(input_ids).unsqueeze(0).to(self.device) output_ids = torch.LongTensor(output_ids).unsqueeze(0).to(self.device) try: with torch.no_grad(): outputs = self.model( input_ids=input_ids, labels=output_ids, output_hidden_states=True ) loss, logits, hidden_states = outputs[0], outputs[1], outputs.hidden_states[0] loss = loss.item() score = -loss score_list.append(score) print('score: ',score) except RuntimeError: # traceback.print_exc() print('input_ids: ',input_ids) print('output_ids: ', output_ids) print(f'source: {src}') print(f'target: {tgt}') # exit(0) return score_list
3,445
41.54321
94
py
GPTScore
GPTScore-main/flan_score.py
# %% import torch import torch.nn as nn import traceback from transformers import AutoModelForSeq2SeqLM, AutoTokenizer class FLANScorer: def __init__(self, device='cuda:0', max_length=1024, checkpoint='google/flan-t5-base'): # Set up model self.device = device self.max_length = max_length self.tokenizer = AutoTokenizer.from_pretrained(checkpoint) self.model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint) self.model.eval() self.model.to(device) # Set up loss self.loss_fct = nn.NLLLoss(reduction='none', ignore_index=self.model.config.pad_token_id) self.lsm = nn.LogSoftmax(dim=1) def load(self): """ Load model from paraphrase finetuning """ self.model.load_state_dict(torch.load('models/bart.pth', map_location=self.device)) def score(self, srcs, tgts, batch_size): """ Score a batch of examples """ score_list = [] for i in range(0, len(srcs), batch_size): src_list = srcs[i: i + batch_size] tgt_list = tgts[i: i + batch_size] if i <1: print('src_list: ',src_list) print('tgt_list: ', tgt_list) try: with torch.no_grad(): encoded_src = self.tokenizer( src_list, max_length=self.max_length, truncation=True, padding=True, return_tensors='pt' ) encoded_tgt = self.tokenizer( tgt_list, max_length=self.max_length, truncation=True, padding=True, return_tensors='pt' ) src_tokens = encoded_src['input_ids'].to(self.device) src_mask = encoded_src['attention_mask'].to(self.device) tgt_tokens = encoded_tgt['input_ids'].to(self.device) tgt_mask = encoded_tgt['attention_mask'] tgt_len = tgt_mask.sum(dim=1).to(self.device) output = self.model( input_ids=src_tokens, attention_mask=src_mask, labels=tgt_tokens ) logits = output.logits.view(-1, self.model.config.vocab_size) loss = self.loss_fct(self.lsm(logits), tgt_tokens.view(-1)) loss = loss.view(tgt_tokens.shape[0], -1) loss = loss.sum(dim=1) / tgt_len curr_score_list = [-x.item() for x in loss] score_list += curr_score_list except RuntimeError: traceback.print_exc() print(f'source: {src_list}') print(f'target: {tgt_list}') exit(0) return score_list
2,981
39.849315
97
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/main.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ import argparse import time import yaml import os import logging from collections import OrderedDict from contextlib import suppress from datetime import datetime import models import torch import torch.nn as nn import torchvision.utils from torch.nn.parallel import DistributedDataParallel as NativeDDP from timm.data import Dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset from timm.models import load_checkpoint, create_model, resume_checkpoint, convert_splitbn_model from timm.utils import * from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy, JsdCrossEntropy from timm.optim import create_optimizer from timm.scheduler import create_scheduler from timm.utils import ApexScaler, NativeScaler from checkpoint_saver import CheckpointSaver from labeled_memcached_dataset import McDataset torch.backends.cudnn.benchmark = True _logger = logging.getLogger('train') import warnings warnings.filterwarnings('ignore') config_parser = parser = argparse.ArgumentParser(description='Training Config', add_help=False) parser.add_argument('-c', '--config', default='', type=str, metavar='FILE', help='YAML config file specifying default arguments') parser = argparse.ArgumentParser(description='CSWin Training and Evaluating') # Dataset / Model parameters parser.add_argument('--data', default='/mnt/blob/testset/ImageNet', metavar='DIR', help='path to dataset') parser.add_argument('--model', default='CSWin_64_12211_tiny_224', type=str, metavar='MODEL', help='Name of model to train (default: "countception"') parser.add_argument('--pretrained', action='store_true', default=False, help='Start with pretrained version of specified network (if avail)') parser.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH', help='Initialize model from this checkpoint (default: none)') parser.add_argument('--resume', default='', type=str, metavar='PATH', help='Resume full model and optimizer state from checkpoint (default: none)') parser.add_argument('--eval_checkpoint', default='', type=str, metavar='PATH', help='path to eval checkpoint (default: none)') parser.add_argument('--no-resume-opt', action='store_true', default=False, help='prevent resume of optimizer state when resuming model') parser.add_argument('--num-classes', type=int, default=1000, metavar='N', help='number of label classes (default: 1000)') parser.add_argument('--gp', default=None, type=str, metavar='POOL', help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.') parser.add_argument('--img-size', type=int, default=224, metavar='N', help='Image patch size (default: None => model default)') parser.add_argument('--crop-pct', default=None, type=float, metavar='N', help='Input image center crop percent (for validation only)') parser.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN', help='Override mean pixel value of dataset') parser.add_argument('--std', type=float, nargs='+', default=None, metavar='STD', help='Override std deviation of of dataset') parser.add_argument('--interpolation', default='', type=str, metavar='NAME', help='Image resize interpolation type (overrides model)') parser.add_argument('-b', '--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('-vb', '--validation-batch-size-multiplier', type=int, default=1, metavar='N', help='ratio of validation batch size to training batch size (default: 1)') # Optimizer parameters parser.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER', help='Optimizer (default: "adamw"') parser.add_argument('--opt-eps', default=None, type=float, metavar='EPSILON', help='Optimizer Epsilon (default: None, use opt default)') parser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA', help='Optimizer Betas (default: None, use opt default)') parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='Optimizer momentum (default: 0.9)') parser.add_argument('--weight-decay', type=float, default=0.05, help='weight decay (default: 0.005 for adamw)') parser.add_argument('--clip-grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') # Learning rate schedule parameters parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER', help='LR scheduler (default: "cosine"') parser.add_argument('--lr', type=float, default=5e-4, metavar='LR', help='learning rate (default: 0.01)') parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', help='learning rate noise on/off epoch percentages') parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', help='learning rate noise limit percent (default: 0.67)') parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', help='learning rate noise std-dev (default: 1.0)') parser.add_argument('--lr-cycle-mul', type=float, default=1.0, metavar='MULT', help='learning rate cycle len multiplier (default: 1.0)') parser.add_argument('--lr-cycle-limit', type=int, default=1, metavar='N', help='learning rate cycle limit') parser.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR', help='warmup learning rate (default: 0.0001)') parser.add_argument('--min-lr', type=float, default=1e-5, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') parser.add_argument('--epochs', type=int, default=300, metavar='N', help='number of epochs to train (default: 2)') parser.add_argument('--start-epoch', default=None, type=int, metavar='N', help='manual epoch number (useful on restarts)') parser.add_argument('--decay-epochs', type=float, default=30, metavar='N', help='epoch interval to decay LR') parser.add_argument('--warmup-epochs', type=int, default=20, metavar='N', help='epochs to warmup LR, if scheduler supports') parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N', help='epochs to cooldown LR at min_lr, after cyclic schedule ends') parser.add_argument('--patience-epochs', type=int, default=10, metavar='N', help='patience epochs for Plateau LR scheduler (default: 10') parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE', help='LR decay rate (default: 0.1)') # Augmentation & regularization parameters parser.add_argument('--no-aug', action='store_true', default=False, help='Disable all training augmentation, override other train aug args') parser.add_argument('--scale', type=float, nargs='+', default=[0.08, 1.0], metavar='PCT', help='Random resize scale (default: 0.08 1.0)') parser.add_argument('--ratio', type=float, nargs='+', default=[3./4., 4./3.], metavar='RATIO', help='Random resize aspect ratio (default: 0.75 1.33)') parser.add_argument('--hflip', type=float, default=0.5, help='Horizontal flip training aug probability') parser.add_argument('--vflip', type=float, default=0., help='Vertical flip training aug probability') parser.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT', help='Color jitter factor (default: 0.4)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". (default: None)'), parser.add_argument('--aug-splits', type=int, default=0, help='Number of augmentation splits (default: 0, valid: 0 or >=2)') parser.add_argument('--jsd', action='store_true', default=False, help='Enable Jensen-Shannon Divergence + CE loss. Use with `--aug-splits`.') parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "const")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0. (default: 0.)') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0. (default: 0.)') parser.add_argument('--cutmix-minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup-prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup-switch-prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup-mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') parser.add_argument('--mixup-off-epoch', default=0, type=int, metavar='N', help='Turn off mixup after this epoch, disabled if 0 (default: 0)') parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') parser.add_argument('--train-interpolation', type=str, default='random', help='Training interpolation (random, bilinear, bicubic default: "random")') parser.add_argument('--drop', type=float, default=0.0, metavar='PCT', help='Dropout rate (default: 0.0)') parser.add_argument('--drop-connect', type=float, default=None, metavar='PCT', help='Drop connect rate, DEPRECATED, use drop-path (default: None)') parser.add_argument('--drop-path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: None)') parser.add_argument('--drop-block', type=float, default=None, metavar='PCT', help='Drop block rate (default: None)') # Batch norm parameters (only works with gen_efficientnet based models currently) parser.add_argument('--bn-tf', action='store_true', default=False, help='Use Tensorflow BatchNorm defaults for models that support it (default: False)') parser.add_argument('--bn-momentum', type=float, default=None, help='BatchNorm momentum override (if not None)') parser.add_argument('--bn-eps', type=float, default=None, help='BatchNorm epsilon override (if not None)') parser.add_argument('--sync-bn', action='store_true', help='Enable NVIDIA Apex or Torch synchronized BatchNorm.') parser.add_argument('--dist-bn', type=str, default='', help='Distribute BatchNorm stats between nodes after each epoch ("broadcast", "reduce", or "")') parser.add_argument('--split-bn', action='store_true', help='Enable separate BN layers per augmentation split.') # Model Exponential Moving Average parser.add_argument('--model-ema', action='store_true', default=True, help='Enable tracking moving average of model weights') parser.add_argument('--model-ema-force-cpu', action='store_true', default=False, help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.') parser.add_argument('--model-ema-decay', type=float, default=0.99992, help='decay factor for model weights moving average (default: 0.9998)') # Misc parser.add_argument('--seed', type=int, default=42, metavar='S', help='random seed (default: 42)') parser.add_argument('--log-interval', type=int, default=50, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--recovery-interval', type=int, default=0, metavar='N', help='how many batches to wait before writing recovery checkpoint') parser.add_argument('-j', '--workers', type=int, default=8, metavar='N', help='how many training processes to use (default: 1)') parser.add_argument('--num-gpu', type=int, default=1, help='Number of GPUS to use') parser.add_argument('--save-images', action='store_true', default=False, help='save images of input bathes every log interval for debugging') parser.add_argument('--amp', action='store_true', default=False, help='use NVIDIA Apex AMP or Native AMP for mixed precision training') parser.add_argument('--apex-amp', action='store_true', default=False, help='Use NVIDIA Apex AMP mixed precision') parser.add_argument('--native-amp', action='store_true', default=False, help='Use Native Torch AMP mixed precision') parser.add_argument('--channels-last', action='store_true', default=False, help='Use channels_last memory layout') parser.add_argument('--pin-mem', action='store_true', default=False, help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no-prefetcher', action='store_true', default=False, help='disable fast prefetcher') parser.add_argument('--output', default='', type=str, metavar='PATH', help='path to output folder (default: none, current dir)') parser.add_argument('--eval-metric', default='top1', type=str, metavar='EVAL_METRIC', help='Best metric (default: "top1"') parser.add_argument('--tta', type=int, default=0, metavar='N', help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)') parser.add_argument("--local_rank", default=0, type=int) parser.add_argument('--use-multi-epochs-loader', action='store_true', default=False, help='use the multi-epochs-loader to save time at the beginning of every epoch') parser.add_argument('--use-chk', action='store_true', default=False, help='Enable tracking moving average of model weights') has_apex = False has_native_amp = False try: if getattr(torch.cuda.amp, 'autocast') is not None: has_native_amp = True except AttributeError: pass def _parse_args(): # Do we have a config file to parse? args_config, remaining = config_parser.parse_known_args() if args_config.config: with open(args_config.config, 'r') as f: cfg = yaml.safe_load(f) parser.set_defaults(**cfg) # The main arg parser parses the rest of the args, the usual # defaults will have been overridden if config file specified. args = parser.parse_args(remaining) # Cache the args as a text string to save them in the output dir later args_text = yaml.safe_dump(args.__dict__, default_flow_style=False) return args, args_text def main(): setup_default_logging() args, args_text = _parse_args() args.prefetcher = not args.no_prefetcher args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1 if args.distributed and args.num_gpu > 1: _logger.warning( 'Using more than one GPU per process in distributed mode is not allowed.Setting num_gpu to 1.') args.num_gpu = 1 args.device = 'cuda:0' args.world_size = 1 args.rank = 0 # global rank if args.distributed: args.num_gpu = 1 args.device = 'cuda:%d' % args.local_rank torch.cuda.set_device(args.local_rank) torch.distributed.init_process_group(backend='nccl', init_method='env://') args.world_size = torch.distributed.get_world_size() args.rank = torch.distributed.get_rank() assert args.rank >= 0 if args.distributed: _logger.info('Training in distributed mode with multiple processes, 1 GPU per process. Process %d, total %d.' % (args.rank, args.world_size)) else: _logger.info('Training with a single process on %d GPUs.' % args.num_gpu) torch.manual_seed(args.seed + args.rank) model = create_model( args.model, pretrained=args.pretrained, num_classes=args.num_classes, drop_rate=args.drop, drop_connect_rate=args.drop_connect, # DEPRECATED, use drop_path drop_path_rate=args.drop_path, drop_block_rate=args.drop_block, global_pool=args.gp, bn_tf=args.bn_tf, bn_momentum=args.bn_momentum, bn_eps=args.bn_eps, checkpoint_path=args.initial_checkpoint, img_size=args.img_size, use_chk=args.use_chk) def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) print ('Num:', count_parameters(model)/1e6) if args.local_rank == 0: _logger.info('Model %s created, param count: %d' % (args.model, sum([m.numel() for m in model.parameters()]))) data_config = resolve_data_config(vars(args), model=model, verbose=args.local_rank == 0) num_aug_splits = 0 if args.aug_splits > 0: assert args.aug_splits > 1, 'A split of 1 makes no sense' num_aug_splits = args.aug_splits if args.split_bn: assert num_aug_splits > 1 or args.resplit model = convert_splitbn_model(model, max(num_aug_splits, 2)) use_amp = None if args.amp: # for backwards compat, `--amp` arg tries apex before native amp if has_apex: args.apex_amp = True elif has_native_amp: args.native_amp = True if args.apex_amp and has_apex: use_amp = 'apex' elif args.native_amp and has_native_amp: use_amp = 'native' elif args.apex_amp or args.native_amp: _logger.warning("Neither APEX or native Torch AMP is available, using float32. " "Install NVIDA apex or upgrade to PyTorch 1.6") if args.num_gpu > 1: if use_amp == 'apex': _logger.warning( 'Apex AMP does not work well with nn.DataParallel, disabling. Use DDP or Torch AMP.') use_amp = None model = nn.DataParallel(model, device_ids=list(range(args.num_gpu))).cuda() assert not args.channels_last, "Channels last not supported with DP, use DDP." else: model.cuda() if args.channels_last: model = model.to(memory_format=torch.channels_last) optimizer = create_optimizer(args, model) amp_autocast = suppress # do nothing loss_scaler = None if use_amp == 'apex': model, optimizer = amp.initialize(model, optimizer, opt_level='O1') loss_scaler = ApexScaler() if args.local_rank == 0: _logger.info('Using NVIDIA APEX AMP. Training in mixed precision.') elif use_amp == 'native': amp_autocast = torch.cuda.amp.autocast loss_scaler = NativeScaler() if args.local_rank == 0: _logger.info('Using native Torch AMP. Training in mixed precision.') else: if args.local_rank == 0: _logger.info('AMP not enabled. Training in float32.') # optionally resume from a checkpoint resume_epoch = None if args.resume: resume_epoch = resume_checkpoint( model, args.resume, optimizer=None if args.no_resume_opt else optimizer, loss_scaler=None if args.no_resume_opt else loss_scaler, log_info=args.local_rank == 0) model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper model_ema = ModelEma( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else '', resume=args.resume) if args.distributed: if args.sync_bn: assert not args.split_bn try: if has_apex and use_amp != 'native': # Apex SyncBN preferred unless native amp is activated model = convert_syncbn_model(model) else: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) if args.local_rank == 0: _logger.info( 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using ' 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.') except Exception as e: _logger.error('Failed to enable Synchronized BatchNorm. Install Apex or Torch >= 1.1') if has_apex and use_amp != 'native': # Apex DDP preferred unless native amp is activated if args.local_rank == 0: _logger.info("Using NVIDIA APEX DistributedDataParallel.") model = ApexDDP(model, delay_allreduce=True) else: if args.local_rank == 0: _logger.info("Using native Torch DistributedDataParallel.") model = NativeDDP(model, device_ids=[args.local_rank], find_unused_parameters=True) # can use device str in Torch >= 1.1 # NOTE: EMA model does not need to be wrapped by DDP lr_scheduler, num_epochs = create_scheduler(args, optimizer) start_epoch = 0 if args.start_epoch is not None: # a specified start_epoch will always override the resume epoch start_epoch = args.start_epoch elif resume_epoch is not None: start_epoch = resume_epoch if lr_scheduler is not None and start_epoch > 0: lr_scheduler.step(start_epoch) if args.local_rank == 0: _logger.info('Scheduled epochs: {}'.format(num_epochs)) train_dir = os.path.join(args.data, 'train') if not os.path.exists(train_dir): _logger.error('Training folder does not exist at: {}'.format(train_dir)) exit(1) dataset_train = McDataset(args.data, './dataset/ILSVRC2012_name_train.txt', 'train') collate_fn = None mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: mixup_args = dict( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.num_classes) if args.prefetcher: assert not num_aug_splits # collate conflict (need to support deinterleaving in collate mixup) collate_fn = FastCollateMixup(**mixup_args) else: mixup_fn = Mixup(**mixup_args) if num_aug_splits > 1: dataset_train = AugMixDataset(dataset_train, num_splits=num_aug_splits) train_interpolation = args.train_interpolation if args.no_aug or not train_interpolation: train_interpolation = data_config['interpolation'] if args.aa == 'None': args.aa = None loader_train = create_loader( dataset_train, input_size=data_config['input_size'], batch_size=args.batch_size, is_training=True, use_prefetcher=args.prefetcher, no_aug=args.no_aug, re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, re_split=args.resplit, scale=args.scale, ratio=args.ratio, hflip=args.hflip, vflip=args.vflip, color_jitter=args.color_jitter, auto_augment=args.aa, num_aug_splits=num_aug_splits, interpolation=train_interpolation, mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, collate_fn=collate_fn, pin_memory=args.pin_mem, use_multi_epochs_loader=args.use_multi_epochs_loader ) eval_dir = os.path.join(args.data, 'val') if not os.path.isdir(eval_dir): eval_dir = os.path.join(args.data, 'validation') if not os.path.isdir(eval_dir): _logger.error('Validation folder does not exist at: {}'.format(eval_dir)) exit(1) dataset_eval = McDataset(args.data, './dataset/ILSVRC2012_name_val.txt', 'val') loader_eval = create_loader( dataset_eval, input_size=data_config['input_size'], batch_size=args.validation_batch_size_multiplier * args.batch_size, is_training=False, use_prefetcher=args.prefetcher, interpolation=data_config['interpolation'], mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, crop_pct=data_config['crop_pct'], pin_memory=args.pin_mem, ) if args.jsd: assert num_aug_splits > 1 # JSD only valid with aug splits set train_loss_fn = JsdCrossEntropy(num_splits=num_aug_splits, smoothing=args.smoothing).cuda() elif mixup_active: # smoothing is handled with mixup target transform train_loss_fn = SoftTargetCrossEntropy().cuda() elif args.smoothing: train_loss_fn = LabelSmoothingCrossEntropy(smoothing=args.smoothing).cuda() else: train_loss_fn = nn.CrossEntropyLoss().cuda() validate_loss_fn = nn.CrossEntropyLoss().cuda() eval_metric = args.eval_metric best_metric = None best_epoch = None if args.eval_checkpoint: # evaluate the model load_checkpoint(model, args.eval_checkpoint, args.model_ema) val_metrics = validate(model, loader_eval, validate_loss_fn, args) print(f"Top-1 accuracy of the model is: {val_metrics['top1']:.1f}%") return saver = None output_dir = '' if args.local_rank == 0: output_base = args.output if args.output else './output' exp_name = '-'.join([ datetime.now().strftime("%Y%m%d-%H%M%S"), args.model, str(data_config['input_size'][-1]) ]) output_dir = get_outdir(output_base, 'train', exp_name) decreasing = True if eval_metric == 'loss' else False saver = CheckpointSaver( model=model, optimizer=optimizer, args=args, model_ema=model_ema, amp_scaler=loss_scaler, checkpoint_dir=output_dir, recovery_dir=output_dir, decreasing=decreasing) with open(os.path.join(output_dir, 'args.yaml'), 'w') as f: f.write(args_text) try: # train the model for epoch in range(start_epoch, num_epochs): if args.distributed: loader_train.sampler.set_epoch(epoch) train_metrics = train_epoch( epoch, model, loader_train, optimizer, train_loss_fn, args, lr_scheduler=lr_scheduler, saver=saver, output_dir=output_dir, amp_autocast=amp_autocast, loss_scaler=loss_scaler, model_ema=model_ema, mixup_fn=mixup_fn) if args.distributed and args.dist_bn in ('broadcast', 'reduce'): if args.local_rank == 0: _logger.info("Distributing BatchNorm running means and vars") distribute_bn(model, args.world_size, args.dist_bn == 'reduce') eval_metrics = validate(model, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast) if model_ema is not None and not args.model_ema_force_cpu: if args.distributed and args.dist_bn in ('broadcast', 'reduce'): distribute_bn(model_ema, args.world_size, args.dist_bn == 'reduce') ema_eval_metrics = validate( model_ema.ema, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast, log_suffix=' (EMA)') eval_metrics = ema_eval_metrics if lr_scheduler is not None: # step LR for next epoch lr_scheduler.step(epoch + 1, eval_metrics[eval_metric]) update_summary( epoch, train_metrics, eval_metrics, os.path.join(output_dir, 'summary.csv'), write_header=best_metric is None) if saver is not None: # save proper checkpoint with eval metric save_metric = eval_metrics[eval_metric] best_metric, best_epoch = saver.save_checkpoint(epoch, metric=save_metric) except KeyboardInterrupt: pass if best_metric is not None: _logger.info('*** Best metric: {0} (epoch {1})'.format(best_metric, best_epoch)) def train_epoch( epoch, model, loader, optimizer, loss_fn, args, lr_scheduler=None, saver=None, output_dir='', amp_autocast=suppress, loss_scaler=None, model_ema=None, mixup_fn=None): if args.mixup_off_epoch and epoch >= args.mixup_off_epoch: if args.prefetcher and loader.mixup_enabled: loader.mixup_enabled = False elif mixup_fn is not None: mixup_fn.mixup_enabled = False second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order batch_time_m = AverageMeter() data_time_m = AverageMeter() losses_m = AverageMeter() top1_m = AverageMeter() top5_m = AverageMeter() model.train() end = time.time() last_idx = len(loader) - 1 num_updates = epoch * len(loader) for batch_idx, (input, target) in enumerate(loader): last_batch = batch_idx == last_idx data_time_m.update(time.time() - end) if not args.prefetcher: input, target = input.cuda(), target.cuda() if mixup_fn is not None: input, target = mixup_fn(input, target) if args.channels_last: input = input.contiguous(memory_format=torch.channels_last) with amp_autocast(): output = model(input) loss = loss_fn(output, target) if not args.distributed: losses_m.update(loss.item(), input.size(0)) optimizer.zero_grad() if loss_scaler is not None: loss_scaler( loss, optimizer, clip_grad=args.clip_grad, parameters=model.parameters(), create_graph=second_order) else: loss.backward(create_graph=second_order) if args.clip_grad is not None: torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip_grad) optimizer.step() torch.cuda.synchronize() if model_ema is not None: model_ema.update(model) num_updates += 1 batch_time_m.update(time.time() - end) if last_batch or batch_idx % args.log_interval == 0: lrl = [param_group['lr'] for param_group in optimizer.param_groups] lr = sum(lrl) / len(lrl) if args.distributed: reduced_loss = reduce_tensor(loss.data, args.world_size) losses_m.update(reduced_loss.item(), input.size(0)) if args.local_rank == 0: _logger.info( 'Train: {} [{:>4d}/{} ({:>3.0f}%)] ' 'Loss: {loss.val:>9.6f} ({loss.avg:>6.4f}) ' 'Time: {rate:>4.0f}/s ({rate_avg:>4.0f}/s) ' 'LR: {lr:.3e} ' 'Data: {data_time.sum:.3f}'.format( epoch, batch_idx, len(loader), 100. * batch_idx / last_idx, loss=losses_m, batch_time=batch_time_m, rate=input.size(0) * args.world_size / batch_time_m.val, rate_avg=input.size(0) * args.world_size / batch_time_m.avg, lr=lr, data_time=data_time_m)) if args.save_images and output_dir: torchvision.utils.save_image( input, os.path.join(output_dir, 'train-batch-%d.jpg' % batch_idx), padding=0, normalize=True) if saver is not None and args.recovery_interval and ( last_batch or (batch_idx + 1) % args.recovery_interval == 0): saver.save_recovery(epoch, batch_idx=batch_idx) if lr_scheduler is not None: lr_scheduler.step_update(num_updates=num_updates, metric=losses_m.avg) end = time.time() # end for if hasattr(optimizer, 'sync_lookahead'): optimizer.sync_lookahead() return OrderedDict([('loss', losses_m.avg)]) def validate(model, loader, loss_fn, args, amp_autocast=suppress, log_suffix=''): batch_time_m = AverageMeter() losses_m = AverageMeter() top1_m = AverageMeter() top5_m = AverageMeter() model.eval() end = time.time() last_idx = len(loader) - 1 with torch.no_grad(): for batch_idx, (input, target) in enumerate(loader): last_batch = batch_idx == last_idx if not args.prefetcher: input = input.cuda() target = target.cuda() if args.channels_last: input = input.contiguous(memory_format=torch.channels_last) with amp_autocast(): output = model(input) if isinstance(output, (tuple, list)): output = output[0] # augmentation reduction reduce_factor = args.tta if reduce_factor > 1: output = output.unfold(0, reduce_factor, reduce_factor).mean(dim=2) target = target[0:target.size(0):reduce_factor] loss = loss_fn(output, target) acc1, acc5 = accuracy(output, target, topk=(1, 5)) if args.distributed: reduced_loss = reduce_tensor(loss.data, args.world_size) acc1 = reduce_tensor(acc1, args.world_size) acc5 = reduce_tensor(acc5, args.world_size) else: reduced_loss = loss.data torch.cuda.synchronize() losses_m.update(reduced_loss.item(), input.size(0)) top1_m.update(acc1.item(), output.size(0)) top5_m.update(acc5.item(), output.size(0)) batch_time_m.update(time.time() - end) end = time.time() if args.local_rank == 0 and (last_batch or batch_idx % args.log_interval == 0): log_name = 'Test' + log_suffix _logger.info( '{0}: [{1:>4d}/{2}] ' 'Time: {batch_time.val:.3f} ({batch_time.avg:.3f}) ' 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) ' 'Acc@1: {top1.val:>7.4f} ({top1.avg:>7.4f}) ' 'Acc@5: {top5.val:>7.4f} ({top5.avg:>7.4f})'.format( log_name, batch_idx, last_idx, batch_time=batch_time_m, loss=losses_m, top1=top1_m, top5=top5_m)) metrics = OrderedDict([('loss', losses_m.avg), ('top1', top1_m.avg), ('top5', top5_m.avg)]) return metrics if __name__ == '__main__': main()
36,210
46.272846
133
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/labeled_memcached_dataset.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ from torch.utils.data import Dataset import numpy as np import io from PIL import Image import os import json import random def load_img(filepath): img = Image.open(filepath).convert('RGB') return img class McDataset(Dataset): def __init__(self, data_root, file_list, phase = 'train', transform=None): self.transform = transform self.root = os.path.join(data_root, phase) temp_label = json.load(open('./dataset/imagenet_class_index.json', 'r')) self.labels = {} for i in range(1000): self.labels[temp_label[str(i)][0]] = i self.A_paths = [] self.A_labels = [] with open(file_list, 'r') as f: temp_path = f.readlines() for path in temp_path: label = self.labels[path.split('/')[0]] self.A_paths.append(os.path.join(self.root, path.strip())) self.A_labels.append(label) self.num = len(self.A_paths) self.A_size = len(self.A_paths) def __len__(self): return self.num def __getitem__(self, index): try: return self.load_img(index) except: return self.__getitem__(random.randint(0, self.__len__()-1)) def load_img(self, index): A_path = self.A_paths[index % self.A_size] A = load_img(A_path) if self.transform is not None: A = self.transform(A) A_label = self.A_labels[index % self.A_size] return A, A_label
1,700
29.375
80
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/finetune.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ import argparse import time import yaml import os import logging from collections import OrderedDict from contextlib import suppress from datetime import datetime import models import torch import torch.nn as nn import torchvision.utils from torch.nn.parallel import DistributedDataParallel as NativeDDP from timm.data import Dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset from timm.models import create_model, resume_checkpoint, convert_splitbn_model from timm.utils import * from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy, JsdCrossEntropy from timm.scheduler import create_scheduler from timm.utils import ApexScaler, NativeScaler from checkpoint_saver import CheckpointSaver from labeled_memcached_dataset import McDataset import torch.optim as optim torch.backends.cudnn.benchmark = True _logger = logging.getLogger('train') # The first arg parser parses out only the --config argument, this argument is used to # load a yaml file containing key-values that override the defaults for the main parser below config_parser = parser = argparse.ArgumentParser(description='Training Config', add_help=False) parser.add_argument('-c', '--config', default='', type=str, metavar='FILE', help='YAML config file specifying default arguments') parser = argparse.ArgumentParser(description='CSWin Training and Evaluating') # Dataset / Model parameters parser.add_argument('--data', default='/mnt/blob/testset/ImageNet', metavar='DIR', help='path to dataset') parser.add_argument('--model', default='', type=str, metavar='MODEL', help='Name of model to train (default: "countception"') parser.add_argument('--pretrained', action='store_true', default=False, help='Start with pretrained version of specified network (if avail)') parser.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH', help='Initialize model from this checkpoint (default: none)') parser.add_argument('--resume', default='', type=str, metavar='PATH', help='Resume full model and optimizer state from checkpoint (default: none)') parser.add_argument('--eval_checkpoint', default='', type=str, metavar='PATH', help='path to eval checkpoint (default: none)') parser.add_argument('--no-resume-opt', action='store_true', default=False, help='prevent resume of optimizer state when resuming model') parser.add_argument('--num-classes', type=int, default=1000, metavar='N', help='number of label classes (default: 1000)') parser.add_argument('--gp', default=None, type=str, metavar='POOL', help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.') parser.add_argument('--img-size', type=int, default=224, metavar='N', help='Image patch size (default: None => model default)') parser.add_argument('--crop-pct', default=None, type=float, metavar='N', help='Input image center crop percent (for validation only)') parser.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN', help='Override mean pixel value of dataset') parser.add_argument('--std', type=float, nargs='+', default=None, metavar='STD', help='Override std deviation of of dataset') parser.add_argument('--interpolation', default='', type=str, metavar='NAME', help='Image resize interpolation type (overrides model)') parser.add_argument('-b', '--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('-vb', '--validation-batch-size-multiplier', type=int, default=1, metavar='N', help='ratio of validation batch size to training batch size (default: 1)') # Optimizer parameters parser.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER', help='Optimizer (default: "adamw"') parser.add_argument('--opt-eps', default=None, type=float, metavar='EPSILON', help='Optimizer Epsilon (default: None, use opt default)') parser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA', help='Optimizer Betas (default: None, use opt default)') parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='Optimizer momentum (default: 0.9)') parser.add_argument('--weight-decay', type=float, default=0.05, help='weight decay (default: 0.005 for adamw)') parser.add_argument('--clip-grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') # Learning rate schedule parameters parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER', help='LR scheduler (default: "cosine"') parser.add_argument('--lr', type=float, default=5e-4, metavar='LR', help='learning rate (default: 0.01)') parser.add_argument('--lr-scale', type=float, default=1e-2, help='learning rate finetune scale(default: 0.01)') parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', help='learning rate noise on/off epoch percentages') parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', help='learning rate noise limit percent (default: 0.67)') parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', help='learning rate noise std-dev (default: 1.0)') parser.add_argument('--lr-cycle-mul', type=float, default=1.0, metavar='MULT', help='learning rate cycle len multiplier (default: 1.0)') parser.add_argument('--lr-cycle-limit', type=int, default=1, metavar='N', help='learning rate cycle limit') parser.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR', help='warmup learning rate (default: 0.0001)') parser.add_argument('--min-lr', type=float, default=1e-5, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') parser.add_argument('--epochs', type=int, default=300, metavar='N', help='number of epochs to train (default: 2)') parser.add_argument('--start-epoch', default=None, type=int, metavar='N', help='manual epoch number (useful on restarts)') parser.add_argument('--decay-epochs', type=float, default=30, metavar='N', help='epoch interval to decay LR') parser.add_argument('--warmup-epochs', type=int, default=5, metavar='N', help='epochs to warmup LR, if scheduler supports') parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N', help='epochs to cooldown LR at min_lr, after cyclic schedule ends') parser.add_argument('--patience-epochs', type=int, default=10, metavar='N', help='patience epochs for Plateau LR scheduler (default: 10') parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE', help='LR decay rate (default: 0.1)') # Augmentation & regularization parameters parser.add_argument('--no-aug', action='store_true', default=False, help='Disable all training augmentation, override other train aug args') parser.add_argument('--scale', type=float, nargs='+', default=[0.08, 1.0], metavar='PCT', help='Random resize scale (default: 0.08 1.0)') parser.add_argument('--ratio', type=float, nargs='+', default=[3./4., 4./3.], metavar='RATIO', help='Random resize aspect ratio (default: 0.75 1.33)') parser.add_argument('--hflip', type=float, default=0.5, help='Horizontal flip training aug probability') parser.add_argument('--vflip', type=float, default=0., help='Vertical flip training aug probability') parser.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT', help='Color jitter factor (default: 0.4)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". (default: None)'), parser.add_argument('--aug-splits', type=int, default=0, help='Number of augmentation splits (default: 0, valid: 0 or >=2)') parser.add_argument('--jsd', action='store_true', default=False, help='Enable Jensen-Shannon Divergence + CE loss. Use with `--aug-splits`.') parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "const")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0. (default: 0.)') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0. (default: 0.)') parser.add_argument('--cutmix-minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup-prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup-switch-prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup-mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') parser.add_argument('--mixup-off-epoch', default=0, type=int, metavar='N', help='Turn off mixup after this epoch, disabled if 0 (default: 0)') parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') parser.add_argument('--train-interpolation', type=str, default='random', help='Training interpolation (random, bilinear, bicubic default: "random")') parser.add_argument('--drop', type=float, default=0.0, metavar='PCT', help='Dropout rate (default: 0.0)') parser.add_argument('--drop-connect', type=float, default=None, metavar='PCT', help='Drop connect rate, DEPRECATED, use drop-path (default: None)') parser.add_argument('--drop-path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: None)') parser.add_argument('--drop-block', type=float, default=None, metavar='PCT', help='Drop block rate (default: None)') # Batch norm parameters (only works with gen_efficientnet based models currently) parser.add_argument('--bn-tf', action='store_true', default=False, help='Use Tensorflow BatchNorm defaults for models that support it (default: False)') parser.add_argument('--bn-momentum', type=float, default=None, help='BatchNorm momentum override (if not None)') parser.add_argument('--bn-eps', type=float, default=None, help='BatchNorm epsilon override (if not None)') parser.add_argument('--sync-bn', action='store_true', help='Enable NVIDIA Apex or Torch synchronized BatchNorm.') parser.add_argument('--dist-bn', type=str, default='', help='Distribute BatchNorm stats between nodes after each epoch ("broadcast", "reduce", or "")') parser.add_argument('--split-bn', action='store_true', help='Enable separate BN layers per augmentation split.') # Model Exponential Moving Average parser.add_argument('--model-ema', action='store_true', default=True, help='Enable tracking moving average of model weights') parser.add_argument('--model-ema-force-cpu', action='store_true', default=False, help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.') parser.add_argument('--model-ema-decay', type=float, default=0.99996, help='decay factor for model weights moving average (default: 0.9998)') # Misc parser.add_argument('--seed', type=int, default=42, metavar='S', help='random seed (default: 42)') parser.add_argument('--log-interval', type=int, default=50, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--recovery-interval', type=int, default=0, metavar='N', help='how many batches to wait before writing recovery checkpoint') parser.add_argument('-j', '--workers', type=int, default=8, metavar='N', help='how many training processes to use (default: 1)') parser.add_argument('--num-gpu', type=int, default=1, help='Number of GPUS to use') parser.add_argument('--save-images', action='store_true', default=False, help='save images of input bathes every log interval for debugging') parser.add_argument('--amp', action='store_true', default=False, help='use NVIDIA Apex AMP or Native AMP for mixed precision training') parser.add_argument('--apex-amp', action='store_true', default=False, help='Use NVIDIA Apex AMP mixed precision') parser.add_argument('--native-amp', action='store_true', default=False, help='Use Native Torch AMP mixed precision') parser.add_argument('--channels-last', action='store_true', default=False, help='Use channels_last memory layout') parser.add_argument('--pin-mem', action='store_true', default=False, help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no-prefetcher', action='store_true', default=False, help='disable fast prefetcher') parser.add_argument('--output', default='', type=str, metavar='PATH', help='path to output folder (default: none, current dir)') parser.add_argument('--eval-metric', default='top1', type=str, metavar='EVAL_METRIC', help='Best metric (default: "top1"') parser.add_argument('--tta', type=int, default=0, metavar='N', help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)') parser.add_argument("--local_rank", default=0, type=int) parser.add_argument('--use-multi-epochs-loader', action='store_true', default=False, help='use the multi-epochs-loader to save time at the beginning of every epoch') parser.add_argument('--finetune', default='', type=str, metavar='PATH', help='finetune full model and optimizer state from checkpoint (default: none)') parser.add_argument('--fine-22k', action='store_true', default=False, help='finetune 22k model') parser.add_argument('--use-chk', action='store_true', default=False, help='Enable tracking moving average of model weights') parser.add_argument('--ema-finetune', action='store_true', default=False, help='Enable tracking moving average of model weights') try: from apex import amp from apex.parallel import DistributedDataParallel as ApexDDP from apex.parallel import convert_syncbn_model has_apex = True except ImportError: has_apex = False has_native_amp = False try: if getattr(torch.cuda.amp, 'autocast') is not None: has_native_amp = True except AttributeError: pass def _parse_args(): # Do we have a config file to parse? args_config, remaining = config_parser.parse_known_args() if args_config.config: with open(args_config.config, 'r') as f: cfg = yaml.safe_load(f) parser.set_defaults(**cfg) # The main arg parser parses the rest of the args, the usual # defaults will have been overridden if config file specified. args = parser.parse_args(remaining) # Cache the args as a text string to save them in the output dir later args_text = yaml.safe_dump(args.__dict__, default_flow_style=False) return args, args_text def load_checkpoint(args, model, checkpoint_path, use_ema=False): if checkpoint_path and os.path.isfile(checkpoint_path): checkpoint = torch.load(checkpoint_path, map_location='cpu') state_dict_key = 'state_dict' model_key = 'model' if isinstance(checkpoint, dict): if use_ema and 'state_dict_ema' in checkpoint: state_dict_key = 'state_dict_ema' if state_dict_key and state_dict_key in checkpoint: new_state_dict = OrderedDict() for k, v in checkpoint[state_dict_key].items(): # strip `module.` prefix name = k[7:] if k.startswith('module') else k if args.fine_22k and 'head' in k: continue new_state_dict[name] = v state_dict = new_state_dict elif model_key and model_key in checkpoint: new_state_dict = OrderedDict() for k, v in checkpoint[model_key].items(): # strip `module.` prefix name = k[7:] if k.startswith('module') else k if args.fine_22k and 'head' in k: continue new_state_dict[name] = v state_dict = new_state_dict else: state_dict = checkpoint if args.local_rank == 0: _logger.info("Loaded {} from checkpoint '{}'".format(state_dict_key, checkpoint_path)) else: if args.local_rank == 0: _logger.error("No checkpoint found at '{}'".format(checkpoint_path)) raise FileNotFoundError() model_dict = model.state_dict() pretrained_dict = state_dict loaded_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} load_dic = [k for k, v in pretrained_dict.items() if k in model_dict] miss_dic = [k for k, v in pretrained_dict.items() if not (k in model_dict)] unexpect_dic = [k for k, v in model_dict.items() if not (k in pretrained_dict)] if args.local_rank == 0: print ("Miss Keys:", miss_dic) print ("Ubexpected Keys:", unexpect_dic) model_dict.update(loaded_dict) model.load_state_dict(model_dict, strict=True) def create_optimizer(args, parameters, filter_bias_and_bn=True): opt_lower = args.opt.lower() weight_decay = args.weight_decay if 'fused' in opt_lower: assert has_apex and torch.cuda.is_available(), 'APEX and CUDA required for fused optimizers' opt_args = dict(lr=args.lr, weight_decay=weight_decay) if hasattr(args, 'opt_eps') and args.opt_eps is not None: opt_args['eps'] = args.opt_eps if hasattr(args, 'opt_betas') and args.opt_betas is not None: opt_args['betas'] = args.opt_betas if hasattr(args, 'opt_args') and args.opt_args is not None: opt_args.update(args.opt_args) opt_split = opt_lower.split('_') opt_lower = opt_split[-1] if opt_lower == 'sgd' or opt_lower == 'nesterov': opt_args.pop('eps', None) optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=True, **opt_args) elif opt_lower == 'momentum': opt_args.pop('eps', None) optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=False, **opt_args) elif opt_lower == 'adam': optimizer = optim.Adam(parameters, **opt_args) elif opt_lower == 'adamw': optimizer = optim.AdamW(parameters, **opt_args) elif opt_lower == 'nadam': optimizer = Nadam(parameters, **opt_args) elif opt_lower == 'radam': optimizer = RAdam(parameters, **opt_args) elif opt_lower == 'adamp': optimizer = AdamP(parameters, wd_ratio=0.01, nesterov=True, **opt_args) elif opt_lower == 'sgdp': optimizer = SGDP(parameters, momentum=args.momentum, nesterov=True, **opt_args) elif opt_lower == 'adadelta': optimizer = optim.Adadelta(parameters, **opt_args) elif opt_lower == 'adafactor': if not args.lr: opt_args['lr'] = None optimizer = Adafactor(parameters, **opt_args) elif opt_lower == 'adahessian': optimizer = Adahessian(parameters, **opt_args) elif opt_lower == 'rmsprop': optimizer = optim.RMSprop(parameters, alpha=0.9, momentum=args.momentum, **opt_args) elif opt_lower == 'rmsproptf': optimizer = RMSpropTF(parameters, alpha=0.9, momentum=args.momentum, **opt_args) elif opt_lower == 'novograd': optimizer = NovoGrad(parameters, **opt_args) elif opt_lower == 'nvnovograd': optimizer = NvNovoGrad(parameters, **opt_args) elif opt_lower == 'fusedsgd': opt_args.pop('eps', None) optimizer = FusedSGD(parameters, momentum=args.momentum, nesterov=True, **opt_args) elif opt_lower == 'fusedmomentum': opt_args.pop('eps', None) optimizer = FusedSGD(parameters, momentum=args.momentum, nesterov=False, **opt_args) elif opt_lower == 'fusedadam': optimizer = FusedAdam(parameters, adam_w_mode=False, **opt_args) elif opt_lower == 'fusedadamw': optimizer = FusedAdam(parameters, adam_w_mode=True, **opt_args) elif opt_lower == 'fusedlamb': optimizer = FusedLAMB(parameters, **opt_args) elif opt_lower == 'fusednovograd': opt_args.setdefault('betas', (0.95, 0.98)) optimizer = FusedNovoGrad(parameters, **opt_args) else: assert False and "Invalid optimizer" raise ValueError if len(opt_split) > 1: if opt_split[0] == 'lookahead': optimizer = Lookahead(optimizer) return optimizer def main(): setup_default_logging() args, args_text = _parse_args() args.prefetcher = not args.no_prefetcher args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1 if args.distributed and args.num_gpu > 1: _logger.warning( 'Using more than one GPU per process in distributed mode is not allowed.Setting num_gpu to 1.') args.num_gpu = 1 args.device = 'cuda:0' args.world_size = 1 args.rank = 0 # global rank if args.distributed: args.num_gpu = 1 args.device = 'cuda:%d' % args.local_rank torch.cuda.set_device(args.local_rank) torch.distributed.init_process_group(backend='nccl', init_method='env://') args.world_size = torch.distributed.get_world_size() args.rank = torch.distributed.get_rank() assert args.rank >= 0 if args.distributed: _logger.info('Training in distributed mode with multiple processes, 1 GPU per process. Process %d, total %d.' % (args.rank, args.world_size)) else: _logger.info('Training with a single process on %d GPUs.' % args.num_gpu) torch.manual_seed(args.seed + args.rank) model = create_model( args.model, pretrained=args.pretrained, num_classes=args.num_classes, drop_rate=args.drop, drop_connect_rate=args.drop_connect, # DEPRECATED, use drop_path drop_path_rate=args.drop_path, drop_block_rate=args.drop_block, global_pool=args.gp, bn_tf=args.bn_tf, bn_momentum=args.bn_momentum, bn_eps=args.bn_eps, checkpoint_path=args.initial_checkpoint, img_size=args.img_size, use_chk=args.use_chk) if args.local_rank == 0: _logger.info('Model %s created, param count: %d' % (args.model, sum([m.numel() for m in model.parameters()]))) data_config = resolve_data_config(vars(args), model=model, verbose=args.local_rank == 0) num_aug_splits = 0 if args.aug_splits > 0: assert args.aug_splits > 1, 'A split of 1 makes no sense' num_aug_splits = args.aug_splits if args.split_bn: assert num_aug_splits > 1 or args.resplit model = convert_splitbn_model(model, max(num_aug_splits, 2)) use_amp = None if args.amp: if has_apex: args.apex_amp = True elif has_native_amp: args.native_amp = True if args.apex_amp and has_apex: use_amp = 'apex' elif args.native_amp and has_native_amp: use_amp = 'native' elif args.apex_amp or args.native_amp: _logger.warning("Neither APEX or native Torch AMP is available, using float32. " "Install NVIDA apex or upgrade to PyTorch 1.6") if args.num_gpu > 1: if use_amp == 'apex': _logger.warning( 'Apex AMP does not work well with nn.DataParallel, disabling. Use DDP or Torch AMP.') use_amp = None model = nn.DataParallel(model, device_ids=list(range(args.num_gpu))).cuda() assert not args.channels_last, "Channels last not supported with DP, use DDP." else: model.cuda() if args.channels_last: model = model.to(memory_format=torch.channels_last) # optionally resume from a checkpoint resume_epoch = None if args.resume: head_para = [] base_para = [] for name, para in model.named_parameters(): if 'head' in name: head_para.append(para) else: base_para.append(para) parameters = [{'params': base_para, 'lr': args.lr_scale * args.lr}, {'params': head_para}] optimizer = create_optimizer(args, parameters) resume_epoch = resume_checkpoint( model, args.resume, optimizer=None if args.no_resume_opt else optimizer, log_info=args.local_rank == 0) if args.finetune: load_checkpoint(args, model, args.finetune, use_ema=args.ema_finetune) model.cuda() model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper if args.local_rank == 0: print ("Use EMA with decay:", args.model_ema_decay) model_ema = ModelEma( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else '', resume=args.resume) head_para = [] base_para = [] if not args.resume: for name, para in model.named_parameters(): if 'head' in name: head_para.append(para) else: base_para.append(para) parameters = [{'params': base_para, 'lr': args.lr_scale * args.lr}, {'params': head_para}] optimizer = create_optimizer(args, parameters) amp_autocast = suppress # do nothing loss_scaler = None if use_amp == 'apex': model, optimizer = amp.initialize(model, optimizer, opt_level='O1') loss_scaler = ApexScaler() if args.local_rank == 0: _logger.info('Using NVIDIA APEX AMP. Training in mixed precision.') elif use_amp == 'native': amp_autocast = torch.cuda.amp.autocast loss_scaler = NativeScaler() if args.local_rank == 0: _logger.info('Using native Torch AMP. Training in mixed precision.') else: if args.local_rank == 0: _logger.info('AMP not enabled. Training in float32.') if args.distributed: if args.sync_bn: assert not args.split_bn try: if has_apex and use_amp != 'native': # Apex SyncBN preferred unless native amp is activated model = convert_syncbn_model(model) else: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) if args.local_rank == 0: _logger.info( 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using ' 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.') except Exception as e: _logger.error('Failed to enable Synchronized BatchNorm. Install Apex or Torch >= 1.1') if has_apex and use_amp != 'native': # Apex DDP preferred unless native amp is activated if args.local_rank == 0: _logger.info("Using NVIDIA APEX DistributedDataParallel.") model = ApexDDP(model, delay_allreduce=True) else: if args.local_rank == 0: _logger.info("Using native Torch DistributedDataParallel.") model = NativeDDP(model, device_ids=[args.local_rank], find_unused_parameters=False) # can use device str in Torch >= 1.1 # NOTE: EMA model does not need to be wrapped by DDP lr_scheduler, num_epochs = create_scheduler(args, optimizer) start_epoch = 0 if args.start_epoch is not None: # a specified start_epoch will always override the resume epoch start_epoch = args.start_epoch elif resume_epoch is not None: start_epoch = resume_epoch if lr_scheduler is not None and start_epoch > 0: lr_scheduler.step(start_epoch) if args.local_rank == 0: _logger.info('Scheduled epochs: {}'.format(num_epochs)) train_dir = os.path.join(args.data, 'train') if not os.path.exists(train_dir): _logger.error('Training folder does not exist at: {}'.format(train_dir)) exit(1) dataset_train = McDataset(args.data, './dataset/ILSVRC2012_name_train.txt', 'train') collate_fn = None mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: mixup_args = dict( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.num_classes) if args.prefetcher: assert not num_aug_splits # collate conflict (need to support deinterleaving in collate mixup) collate_fn = FastCollateMixup(**mixup_args) else: mixup_fn = Mixup(**mixup_args) if num_aug_splits > 1: dataset_train = AugMixDataset(dataset_train, num_splits=num_aug_splits) train_interpolation = args.train_interpolation if args.no_aug or not train_interpolation: train_interpolation = data_config['interpolation'] if args.aa == 'None': args.aa = None loader_train = create_loader( dataset_train, input_size=data_config['input_size'], batch_size=args.batch_size, is_training=True, use_prefetcher=args.prefetcher, no_aug=args.no_aug, re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, re_split=args.resplit, scale=args.scale, ratio=args.ratio, hflip=args.hflip, vflip=args.vflip, color_jitter=args.color_jitter, auto_augment=args.aa, num_aug_splits=num_aug_splits, interpolation=train_interpolation, mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, collate_fn=collate_fn, pin_memory=args.pin_mem, use_multi_epochs_loader=args.use_multi_epochs_loader ) eval_dir = os.path.join(args.data, 'val') if not os.path.isdir(eval_dir): eval_dir = os.path.join(args.data, 'validation') if not os.path.isdir(eval_dir): _logger.error('Validation folder does not exist at: {}'.format(eval_dir)) exit(1) dataset_eval = McDataset(args.data, './dataset/ILSVRC2012_name_val.txt', 'val') loader_eval = create_loader( dataset_eval, input_size=data_config['input_size'], batch_size=args.validation_batch_size_multiplier * args.batch_size, is_training=False, use_prefetcher=args.prefetcher, interpolation=data_config['interpolation'], mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, crop_pct=data_config['crop_pct'], pin_memory=args.pin_mem, ) if args.jsd: assert num_aug_splits > 1 # JSD only valid with aug splits set train_loss_fn = JsdCrossEntropy(num_splits=num_aug_splits, smoothing=args.smoothing).cuda() elif mixup_active: # smoothing is handled with mixup target transform train_loss_fn = SoftTargetCrossEntropy().cuda() elif args.smoothing: train_loss_fn = LabelSmoothingCrossEntropy(smoothing=args.smoothing).cuda() else: train_loss_fn = nn.CrossEntropyLoss().cuda() validate_loss_fn = nn.CrossEntropyLoss().cuda() eval_metric = args.eval_metric best_metric = None best_epoch = None if args.eval_checkpoint: # evaluate the model load_checkpoint(model, args.eval_checkpoint, args.model_ema) val_metrics = validate(model, loader_eval, validate_loss_fn, args) print(f"Top-1 accuracy of the model is: {val_metrics['top1']:.1f}%") return saver = None output_dir = '' if args.local_rank == 0: output_base = args.output if args.output else './output' exp_name = '-'.join([ datetime.now().strftime("%Y%m%d-%H%M%S"), args.model, str(data_config['input_size'][-1]) ]) output_dir = get_outdir(output_base, 'finetune', exp_name) decreasing = True if eval_metric == 'loss' else False saver = CheckpointSaver( model=model, optimizer=optimizer, args=args, model_ema=model_ema, amp_scaler=loss_scaler, checkpoint_dir=output_dir, recovery_dir=output_dir, decreasing=decreasing) with open(os.path.join(output_dir, 'args.yaml'), 'w') as f: f.write(args_text) try: # train the model for epoch in range(start_epoch, num_epochs): if args.distributed: loader_train.sampler.set_epoch(epoch) train_metrics = train_epoch( epoch, model, loader_train, optimizer, train_loss_fn, args, lr_scheduler=lr_scheduler, saver=saver, output_dir=output_dir, amp_autocast=amp_autocast, loss_scaler=loss_scaler, model_ema=model_ema, mixup_fn=mixup_fn) if args.distributed and args.dist_bn in ('broadcast', 'reduce'): if args.local_rank == 0: _logger.info("Distributing BatchNorm running means and vars") distribute_bn(model, args.world_size, args.dist_bn == 'reduce') eval_metrics = validate(model, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast) if model_ema is not None and not args.model_ema_force_cpu: if args.distributed and args.dist_bn in ('broadcast', 'reduce'): distribute_bn(model_ema, args.world_size, args.dist_bn == 'reduce') ema_eval_metrics = validate( model_ema.ema, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast, log_suffix=' (EMA)') eval_metrics = ema_eval_metrics if lr_scheduler is not None: # step LR for next epoch lr_scheduler.step(epoch + 1, eval_metrics[eval_metric]) update_summary( epoch, train_metrics, eval_metrics, os.path.join(output_dir, 'summary.csv'), write_header=best_metric is None) if saver is not None: # save proper checkpoint with eval metric save_metric = eval_metrics[eval_metric] best_metric, best_epoch = saver.save_checkpoint(epoch, metric=save_metric) except KeyboardInterrupt: pass if best_metric is not None: _logger.info('*** Best metric: {0} (epoch {1})'.format(best_metric, best_epoch)) def train_epoch( epoch, model, loader, optimizer, loss_fn, args, freeze=False, lr_scheduler=None, saver=None, output_dir='', amp_autocast=suppress, loss_scaler=None, model_ema=None, mixup_fn=None): if args.mixup_off_epoch and epoch >= args.mixup_off_epoch: if args.prefetcher and loader.mixup_enabled: loader.mixup_enabled = False elif mixup_fn is not None: mixup_fn.mixup_enabled = False second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order batch_time_m = AverageMeter() data_time_m = AverageMeter() losses_m = AverageMeter() top1_m = AverageMeter() top5_m = AverageMeter() model.train() end = time.time() last_idx = len(loader) - 1 num_updates = epoch * len(loader) for batch_idx, (input, target) in enumerate(loader): last_batch = batch_idx == last_idx data_time_m.update(time.time() - end) if not args.prefetcher: input, target = input.cuda(), target.cuda() if mixup_fn is not None: input, target = mixup_fn(input, target) if args.channels_last: input = input.contiguous(memory_format=torch.channels_last) with amp_autocast(): output = model(input) loss = loss_fn(output, target) if not args.distributed: losses_m.update(loss.item(), input.size(0)) #torch.cuda.synchronize() #end = time.time() optimizer.zero_grad() if loss_scaler is not None: loss_scaler( loss, optimizer, clip_grad=args.clip_grad, parameters=model.parameters(), create_graph=second_order) else: loss.backward(create_graph=second_order) if args.clip_grad is not None: torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip_grad) optimizer.step() torch.cuda.synchronize() if model_ema is not None: model_ema.update(model) num_updates += 1 batch_time_m.update(time.time() - end) if last_batch or batch_idx % args.log_interval == 0: lrl = [param_group['lr'] for param_group in optimizer.param_groups] lr = sum(lrl) / len(lrl) if args.distributed: reduced_loss = reduce_tensor(loss.data, args.world_size) losses_m.update(reduced_loss.item(), input.size(0)) if args.local_rank == 0: _logger.info( 'Train:{} [{:>4d}/{} ({:>3.0f}%)] ' 'Loss:{loss.val:>9.6f} ({loss.avg:>6.4f}) ' 'Time:' '({batch_time.avg:.3f}s, {rate_avg:>7.2f}/s) ' 'LR:{lr1:.3e} {lr2:.3e} ' 'Data:({data_time.sum:.3f})'.format( epoch, batch_idx, len(loader), 100. * batch_idx / last_idx, loss=losses_m, batch_time=batch_time_m, rate=input.size(0) * args.world_size / batch_time_m.val, rate_avg=input.size(0) * args.world_size / batch_time_m.avg, lr1=lrl[0], lr2=lrl[1], data_time=data_time_m)) if args.save_images and output_dir: torchvision.utils.save_image( input, os.path.join(output_dir, 'train-batch-%d.jpg' % batch_idx), padding=0, normalize=True) if saver is not None and args.recovery_interval and ( last_batch or (batch_idx + 1) % args.recovery_interval == 0): saver.save_recovery(epoch, batch_idx=batch_idx) if lr_scheduler is not None: lr_scheduler.step_update(num_updates=num_updates, metric=losses_m.avg) end = time.time() # end for if hasattr(optimizer, 'sync_lookahead'): optimizer.sync_lookahead() return OrderedDict([('loss', losses_m.avg)]) def validate(model, loader, loss_fn, args, amp_autocast=suppress, log_suffix=''): batch_time_m = AverageMeter() losses_m = AverageMeter() top1_m = AverageMeter() top5_m = AverageMeter() model.eval() end = time.time() last_idx = len(loader) - 1 with torch.no_grad(): for batch_idx, (input, target) in enumerate(loader): last_batch = batch_idx == last_idx if not args.prefetcher: input = input.cuda() target = target.cuda() if args.channels_last: input = input.contiguous(memory_format=torch.channels_last) with amp_autocast(): output = model(input) if isinstance(output, (tuple, list)): output = output[0] # augmentation reduction reduce_factor = args.tta if reduce_factor > 1: output = output.unfold(0, reduce_factor, reduce_factor).mean(dim=2) target = target[0:target.size(0):reduce_factor] loss = loss_fn(output, target) acc1, acc5 = accuracy(output, target, topk=(1, 5)) if args.distributed: reduced_loss = reduce_tensor(loss.data, args.world_size) acc1 = reduce_tensor(acc1, args.world_size) acc5 = reduce_tensor(acc5, args.world_size) else: reduced_loss = loss.data torch.cuda.synchronize() losses_m.update(reduced_loss.item(), input.size(0)) top1_m.update(acc1.item(), output.size(0)) top5_m.update(acc5.item(), output.size(0)) batch_time_m.update(time.time() - end) end = time.time() if args.local_rank == 0 and (last_batch or batch_idx % args.log_interval == 0): log_name = 'Test' + log_suffix _logger.info( '{0}: [{1:>4d}/{2}] ' 'Time: {batch_time.val:.3f} ({batch_time.avg:.3f}) ' 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) ' 'Acc@1: {top1.val:>7.4f} ({top1.avg:>7.4f}) ' 'Acc@5: {top5.val:>7.4f} ({top5.avg:>7.4f})'.format( log_name, batch_idx, last_idx, batch_time=batch_time_m, loss=losses_m, top1=top1_m, top5=top5_m)) metrics = OrderedDict([('loss', losses_m.avg), ('top1', top1_m.avg), ('top5', top5_m.avg)]) return metrics if __name__ == '__main__': main()
43,476
45.900755
134
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/checkpoint_saver.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ import glob import operator import os import logging import torch from timm.utils.model import unwrap_model, get_state_dict import shutil _logger = logging.getLogger(__name__) class CheckpointSaver: def __init__( self, model, optimizer, args=None, model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='', recovery_dir='', decreasing=False, max_history=10, unwrap_fn=unwrap_model): # objects to save state_dicts of self.model = model self.optimizer = optimizer self.args = args self.model_ema = model_ema self.amp_scaler = amp_scaler # state self.checkpoint_files = [] # (filename, metric) tuples in order of decreasing betterness self.best_epoch = None self.best_metric = None self.curr_recovery_file = '' self.last_recovery_file = '' # config self.checkpoint_dir = checkpoint_dir self.recovery_dir = recovery_dir self.save_prefix = checkpoint_prefix self.recovery_prefix = recovery_prefix self.extension = '.pth.tar' self.decreasing = decreasing # a lower metric is better if True self.cmp = operator.lt if decreasing else operator.gt # True if lhs better than rhs self.max_history = max_history self.unwrap_fn = unwrap_fn assert self.max_history >= 1 def save_checkpoint(self, epoch, metric=None): assert epoch >= 0 tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension) last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension) self._save(tmp_save_path, epoch, metric) if os.path.exists(last_save_path): #os.unlink(last_save_path) # required for Windows support. os.remove(last_save_path) os.rename(tmp_save_path, last_save_path) worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None if (len(self.checkpoint_files) < self.max_history or metric is None or self.cmp(metric, worst_file[1])): if len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension save_path = os.path.join(self.checkpoint_dir, filename) #os.link(last_save_path, save_path) shutil.copyfile(last_save_path, save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files = sorted( self.checkpoint_files, key=lambda x: x[1], reverse=not self.decreasing) # sort in descending order if a lower metric is not better checkpoints_str = "Current checkpoints:\n" for c in self.checkpoint_files: checkpoints_str += ' {}\n'.format(c) _logger.info(checkpoints_str) if metric is not None and (self.best_metric is None or self.cmp(metric, self.best_metric)): self.best_epoch = epoch self.best_metric = metric best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension) if os.path.exists(best_save_path): os.unlink(best_save_path) #os.link(last_save_path, best_save_path) shutil.copyfile(last_save_path, best_save_path) return (None, None) if self.best_metric is None else (self.best_metric, self.best_epoch) def _save(self, save_path, epoch, metric=None): save_state = { 'epoch': epoch, 'arch': type(self.model).__name__.lower(), 'state_dict': get_state_dict(self.model, self.unwrap_fn), 'optimizer': self.optimizer.state_dict(), 'version': 2, # version < 2 increments epoch before save } if self.args is not None: save_state['arch'] = self.args.model save_state['args'] = self.args if self.amp_scaler is not None: save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() if self.model_ema is not None: save_state['state_dict_ema'] = get_state_dict(self.model_ema, self.unwrap_fn) if metric is not None: save_state['metric'] = metric torch.save(save_state, save_path) def _cleanup_checkpoints(self, trim=0): trim = min(len(self.checkpoint_files), trim) delete_index = self.max_history - trim if delete_index <= 0 or len(self.checkpoint_files) <= delete_index: return to_delete = self.checkpoint_files[delete_index:] for d in to_delete: try: _logger.debug("Cleaning checkpoint: {}".format(d)) os.remove(d[0]) except Exception as e: _logger.error("Exception '{}' while deleting checkpoint".format(e)) self.checkpoint_files = self.checkpoint_files[:delete_index] def save_recovery(self, epoch, batch_idx=0): assert epoch >= 0 filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension save_path = os.path.join(self.recovery_dir, filename) self._save(save_path, epoch) if os.path.exists(self.last_recovery_file): try: _logger.debug("Cleaning recovery: {}".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except Exception as e: _logger.error("Exception '{}' while removing {}".format(e, self.last_recovery_file)) self.last_recovery_file = self.curr_recovery_file self.curr_recovery_file = save_path def find_recovery(self): recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix) files = glob.glob(recovery_path + '*' + self.extension) files = sorted(files) if len(files): return files[0] else: return ''
6,397
39.751592
104
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/segmentation/backbone/cswin_transformer.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.helpers import load_pretrained from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.resnet import resnet26d, resnet50d from timm.models.registry import register_model from einops.layers.torch import Rearrange import numpy as np import time from mmcv_custom import load_checkpoint from mmseg.utils import get_root_logger from ..builder import BACKBONES import torch.utils.checkpoint as checkpoint class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class LePEAttention(nn.Module): def __init__(self, dim, resolution, idx, split_size=7, dim_out=None, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): """Not supported now, since we have cls_tokens now..... """ super().__init__() self.dim = dim self.dim_out = dim_out or dim self.resolution = resolution self.split_size = split_size self.num_heads = num_heads head_dim = dim // num_heads # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights self.scale = qk_scale or head_dim ** -0.5 self.idx = idx if idx == -1: H_sp, W_sp = self.resolution, self.resolution elif idx == 0: H_sp, W_sp = self.resolution, self.split_size elif idx == 1: W_sp, H_sp = self.resolution, self.split_size else: print ("ERROR MODE", idx) exit(0) self.H_sp = H_sp self.W_sp = W_sp self.H_sp_ = self.H_sp self.W_sp_ = self.W_sp stride = 1 self.get_v = nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1,groups=dim) self.attn_drop = nn.Dropout(attn_drop) def im2cswin(self, x): B, C, H, W = x.shape x = img2windows(x, self.H_sp, self.W_sp) x = x.reshape(-1, self.H_sp* self.W_sp, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3).contiguous() return x def get_rpe(self, x, func): B, C, H, W = x.shape H_sp, W_sp = self.H_sp, self.W_sp x = x.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp) x = x.permute(0, 2, 4, 1, 3, 5).contiguous().reshape(-1, C, H_sp, W_sp) ### B', C, H', W' rpe = func(x) ### B', C, H', W' rpe = rpe.reshape(-1, self.num_heads, C // self.num_heads, H_sp * W_sp).permute(0, 1, 3, 2).contiguous() x = x.reshape(-1, self.num_heads, C // self.num_heads, self.H_sp* self.W_sp).permute(0, 1, 3, 2).contiguous() return x, rpe def forward(self, temp): """ x: B N C mask: B N N """ B, _, C, H, W = temp.shape idx = self.idx if idx == -1: H_sp, W_sp = H, W elif idx == 0: H_sp, W_sp = H, self.split_size elif idx == 1: H_sp, W_sp = self.split_size, W else: print ("ERROR MODE in forward", idx) exit(0) self.H_sp = H_sp self.W_sp = W_sp ### padding for split window H_pad = (self.H_sp - H % self.H_sp) % self.H_sp W_pad = (self.W_sp - W % self.W_sp) % self.W_sp top_pad = H_pad//2 down_pad = H_pad - top_pad left_pad = W_pad//2 right_pad = W_pad - left_pad H_ = H + H_pad W_ = W + W_pad qkv = F.pad(temp, (left_pad, right_pad, top_pad, down_pad)) ### B,3,C,H',W' qkv = qkv.permute(1, 0, 2, 3, 4) q,k,v = qkv[0], qkv[1], qkv[2] q = self.im2cswin(q) k = self.im2cswin(k) v, rpe = self.get_rpe(v, self.get_v) ### Local attention q = q * self.scale attn = (q @ k.transpose(-2, -1)) # B head N C @ B head C N --> B head N N attn = nn.functional.softmax(attn, dim=-1, dtype=attn.dtype) attn = self.attn_drop(attn) x = (attn @ v) + rpe x = x.transpose(1, 2).reshape(-1, self.H_sp* self.W_sp, C) # B head N N @ B head N C ### Window2Img x = windows2img(x, self.H_sp, self.W_sp, H_, W_) # B H_ W_ C x = x[:, top_pad:H+top_pad, left_pad:W+left_pad, :] x = x.reshape(B, -1, C) return x class CSWinBlock(nn.Module): def __init__(self, dim, patches_resolution, num_heads, split_size=7, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, last_stage=False): super().__init__() self.dim = dim self.num_heads = num_heads self.patches_resolution = patches_resolution self.split_size = split_size self.mlp_ratio = mlp_ratio self.qkv = nn.Linear(dim, dim * 3, bias=True) self.norm1 = norm_layer(dim) if last_stage: self.branch_num = 1 else: self.branch_num = 2 self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(drop) if last_stage: self.attns = nn.ModuleList([ LePEAttention( dim, resolution=self.patches_resolution, idx = -1, split_size=split_size, num_heads=num_heads, dim_out=dim, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) for i in range(self.branch_num)]) else: self.attns = nn.ModuleList([ LePEAttention( dim//2, resolution=self.patches_resolution, idx = i, split_size=split_size, num_heads=num_heads//2, dim_out=dim//2, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) for i in range(self.branch_num)]) mlp_hidden_dim = int(dim * mlp_ratio) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, out_features=dim, act_layer=act_layer, drop=drop) self.norm2 = norm_layer(dim) atten_mask_matrix = None self.register_buffer("atten_mask_matrix", atten_mask_matrix) self.H = None self.W = None def forward(self, x): """ x: B, H*W, C """ B, L, C = x.shape H = self.H W = self.W assert L == H * W, "flatten img_tokens has wrong size" img = self.norm1(x) temp = self.qkv(img).reshape(B, H, W, 3, C).permute(0, 3, 4, 1, 2) if self.branch_num == 2: x1 = self.attns[0](temp[:,:,:C//2,:,:]) x2 = self.attns[1](temp[:,:,C//2:,:,:]) attened_x = torch.cat([x1,x2], dim=2) else: attened_x = self.attns[0](temp) attened_x = self.proj(attened_x) x = x + self.drop_path(attened_x) x = x + self.drop_path(self.mlp(self.norm2(x))) return x def img2windows(img, H_sp, W_sp): """ img: B C H W """ B, C, H, W = img.shape img_reshape = img.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp) img_perm = img_reshape.permute(0, 2, 4, 3, 5, 1).contiguous().reshape(-1, H_sp* W_sp, C) return img_perm def windows2img(img_splits_hw, H_sp, W_sp, H, W): """ img_splits_hw: B' H W C """ B = int(img_splits_hw.shape[0] / (H * W / H_sp / W_sp)) img = img_splits_hw.view(B, H // H_sp, W // W_sp, H_sp, W_sp, -1) img = img.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return img class Merge_Block(nn.Module): def __init__(self, dim, dim_out, norm_layer=nn.LayerNorm): super().__init__() self.conv = nn.Conv2d(dim, dim_out, 3, 2, 1) self.norm = norm_layer(dim_out) def forward(self, x, H, W): B, new_HW, C = x.shape x = x.transpose(-2, -1).contiguous().view(B, C, H, W) x = self.conv(x) B, C, H, W = x.shape x = x.view(B, C, -1).transpose(-2, -1).contiguous() x = self.norm(x) return x, H, W @BACKBONES.register_module() class CSWin(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=64, depth=[1,2,21,1], split_size = 7, num_heads=[1,2,4,8], mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., hybrid_backbone=None, norm_layer=nn.LayerNorm, use_chk=False): super().__init__() self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models heads=num_heads self.use_chk = use_chk self.stage1_conv_embed = nn.Sequential( nn.Conv2d(in_chans, embed_dim, 7, 4, 2), Rearrange('b c h w -> b (h w) c', h = img_size//4, w = img_size//4), nn.LayerNorm(embed_dim) ) self.norm1 = nn.LayerNorm(embed_dim) curr_dim = embed_dim dpr = [x.item() for x in torch.linspace(0, drop_path_rate, np.sum(depth))] # stochastic depth decay rule self.stage1 = nn.ModuleList([ CSWinBlock( dim=curr_dim, num_heads=heads[0], patches_resolution=224//4, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[0], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer) for i in range(depth[0])]) self.merge1 = Merge_Block(curr_dim, curr_dim*(heads[1]//heads[0])) curr_dim = curr_dim*(heads[1]//heads[0]) self.norm2 = nn.LayerNorm(curr_dim) self.stage2 = nn.ModuleList( [CSWinBlock( dim=curr_dim, num_heads=heads[1], patches_resolution=224//8, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[1], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:1])+i], norm_layer=norm_layer) for i in range(depth[1])]) self.merge2 = Merge_Block(curr_dim, curr_dim*(heads[2]//heads[1])) curr_dim = curr_dim*(heads[2]//heads[1]) self.norm3 = nn.LayerNorm(curr_dim) temp_stage3 = [] temp_stage3.extend( [CSWinBlock( dim=curr_dim, num_heads=heads[2], patches_resolution=224//16, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[2], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:2])+i], norm_layer=norm_layer) for i in range(depth[2])]) self.stage3 = nn.ModuleList(temp_stage3) self.merge3 = Merge_Block(curr_dim, curr_dim*(heads[3]//heads[2])) curr_dim = curr_dim*(heads[3]//heads[2]) self.stage4 = nn.ModuleList( [CSWinBlock( dim=curr_dim, num_heads=heads[3], patches_resolution=224//32, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[-1], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:-1])+i], norm_layer=norm_layer, last_stage=True) for i in range(depth[-1])]) self.norm4 = norm_layer(curr_dim) def init_weights(self, pretrained=None): def _init_weights(m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d)): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) if isinstance(pretrained, str): self.apply(_init_weights) logger = get_root_logger() load_checkpoint(self, pretrained, strict=False, logger=logger) elif pretrained is None: self.apply(_init_weights) else: raise TypeError('pretrained must be a str or None') def save_out(self, x, norm, H, W): x = norm(x) B, N, C = x.shape x = x.view(B, H, W, C).permute(0, 3, 1, 2).contiguous() return x def forward_features(self, x): B = x.shape[0] x = self.stage1_conv_embed[0](x) ### B, C, H, W B, C, H, W = x.size() x = x.reshape(B, C, -1).transpose(-1,-2).contiguous() x = self.stage1_conv_embed[2](x) out = [] for blk in self.stage1: blk.H = H blk.W = W if self.use_chk: x = checkpoint.checkpoint(blk, x) else: x = blk(x) out.append(self.save_out(x, self.norm1, H, W)) for pre, blocks, norm in zip([self.merge1, self.merge2, self.merge3], [self.stage2, self.stage3, self.stage4], [self.norm2 , self.norm3 , self.norm4 ]): x, H, W = pre(x, H, W) for blk in blocks: blk.H = H blk.W = W if self.use_chk: x = checkpoint.checkpoint(blk, x) else: x = blk(x) out.append(self.save_out(x, norm, H, W)) return tuple(out) def forward(self, x): x = self.forward_features(x) return x def _conv_filter(state_dict, patch_size=16): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: v = v.reshape((v.shape[0], 3, patch_size, patch_size)) out_dict[k] = v return out_dict
14,811
35.126829
145
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/segmentation/mmcv_custom/checkpoint.py
# Copyright (c) Open-MMLab. All rights reserved. import io import os import os.path as osp import pkgutil import time import warnings from collections import OrderedDict from importlib import import_module from tempfile import TemporaryDirectory import torch import torchvision from torch.optim import Optimizer from torch.utils import model_zoo from torch.nn import functional as F import mmcv from mmcv.fileio import FileClient from mmcv.fileio import load as load_file from mmcv.parallel import is_module_wrapper from mmcv.utils import mkdir_or_exist from mmcv.runner import get_dist_info ENV_MMCV_HOME = 'MMCV_HOME' ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME' DEFAULT_CACHE_DIR = '~/.cache' def _get_mmcv_home(): mmcv_home = os.path.expanduser( os.getenv( ENV_MMCV_HOME, os.path.join( os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'mmcv'))) mkdir_or_exist(mmcv_home) return mmcv_home def load_state_dict(module, state_dict, strict=False, logger=None): """Load state_dict to a module. This method is modified from :meth:`torch.nn.Module.load_state_dict`. Default value for ``strict`` is set to ``False`` and the message for param mismatch will be shown even if strict is False. Args: module (Module): Module that receives the state_dict. state_dict (OrderedDict): Weights. strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Default: ``False``. logger (:obj:`logging.Logger`, optional): Logger to log the error message. If not specified, print function will be used. """ unexpected_keys = [] all_missing_keys = [] err_msg = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if metadata is not None: state_dict._metadata = metadata # use _load_from_state_dict to enable checkpoint version control def load(module, prefix=''): # recursively check parallel module in case that the model has a # complicated structure, e.g., nn.Module(nn.Module(DDP)) if is_module_wrapper(module): module = module.module local_metadata = {} if metadata is None else metadata.get( prefix[:-1], {}) module._load_from_state_dict(state_dict, prefix, local_metadata, True, all_missing_keys, unexpected_keys, err_msg) for name, child in module._modules.items(): if child is not None: load(child, prefix + name + '.') load(module) load = None # break load->load reference cycle # ignore "num_batches_tracked" of BN layers missing_keys = [ key for key in all_missing_keys if 'num_batches_tracked' not in key ] if unexpected_keys: err_msg.append('unexpected key in source ' f'state_dict: {", ".join(unexpected_keys)}\n') if missing_keys: err_msg.append( f'missing keys in source state_dict: {", ".join(missing_keys)}\n') rank, _ = get_dist_info() if len(err_msg) > 0 and rank == 0: err_msg.insert( 0, 'The model and loaded state dict do not match exactly\n') err_msg = '\n'.join(err_msg) if strict: raise RuntimeError(err_msg) elif logger is not None: logger.warning(err_msg) else: print(err_msg) def load_url_dist(url, model_dir=None): """In distributed setting, this function only download checkpoint at local rank 0.""" rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if rank == 0: checkpoint = model_zoo.load_url(url, model_dir=model_dir) if world_size > 1: torch.distributed.barrier() if rank > 0: checkpoint = model_zoo.load_url(url, model_dir=model_dir) return checkpoint def load_pavimodel_dist(model_path, map_location=None): """In distributed setting, this function only download checkpoint at local rank 0.""" try: from pavi import modelcloud except ImportError: raise ImportError( 'Please install pavi to load checkpoint from modelcloud.') rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if rank == 0: model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load(downloaded_file, map_location=map_location) if world_size > 1: torch.distributed.barrier() if rank > 0: model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load( downloaded_file, map_location=map_location) return checkpoint def load_fileclient_dist(filename, backend, map_location): """In distributed setting, this function only download checkpoint at local rank 0.""" rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) allowed_backends = ['ceph'] if backend not in allowed_backends: raise ValueError(f'Load from Backend {backend} is not supported.') if rank == 0: fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) if world_size > 1: torch.distributed.barrier() if rank > 0: fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) return checkpoint def get_torchvision_models(): model_urls = dict() for _, name, ispkg in pkgutil.walk_packages(torchvision.models.__path__): if ispkg: continue _zoo = import_module(f'torchvision.models.{name}') if hasattr(_zoo, 'model_urls'): _urls = getattr(_zoo, 'model_urls') model_urls.update(_urls) return model_urls def get_external_models(): mmcv_home = _get_mmcv_home() default_json_path = osp.join(mmcv.__path__[0], 'model_zoo/open_mmlab.json') default_urls = load_file(default_json_path) assert isinstance(default_urls, dict) external_json_path = osp.join(mmcv_home, 'open_mmlab.json') if osp.exists(external_json_path): external_urls = load_file(external_json_path) assert isinstance(external_urls, dict) default_urls.update(external_urls) return default_urls def get_mmcls_models(): mmcls_json_path = osp.join(mmcv.__path__[0], 'model_zoo/mmcls.json') mmcls_urls = load_file(mmcls_json_path) return mmcls_urls def get_deprecated_model_names(): deprecate_json_path = osp.join(mmcv.__path__[0], 'model_zoo/deprecated.json') deprecate_urls = load_file(deprecate_json_path) assert isinstance(deprecate_urls, dict) return deprecate_urls def _process_mmcls_checkpoint(checkpoint): state_dict = checkpoint['state_dict'] new_state_dict = OrderedDict() for k, v in state_dict.items(): if k.startswith('backbone.'): new_state_dict[k[9:]] = v new_checkpoint = dict(state_dict=new_state_dict) return new_checkpoint def _load_checkpoint(filename, map_location=None): """Load checkpoint from somewhere (modelzoo, file, url). Args: filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str | None): Same as :func:`torch.load`. Default: None. Returns: dict | OrderedDict: The loaded checkpoint. It can be either an OrderedDict storing model weights or a dict containing other information, which depends on the checkpoint. """ if filename.startswith('modelzoo://'): warnings.warn('The URL scheme of "modelzoo://" is deprecated, please ' 'use "torchvision://" instead') model_urls = get_torchvision_models() model_name = filename[11:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('torchvision://'): model_urls = get_torchvision_models() model_name = filename[14:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('open-mmlab://'): model_urls = get_external_models() model_name = filename[13:] deprecated_urls = get_deprecated_model_names() if model_name in deprecated_urls: warnings.warn(f'open-mmlab://{model_name} is deprecated in favor ' f'of open-mmlab://{deprecated_urls[model_name]}') model_name = deprecated_urls[model_name] model_url = model_urls[model_name] # check if is url if model_url.startswith(('http://', 'https://')): checkpoint = load_url_dist(model_url) else: filename = osp.join(_get_mmcv_home(), model_url) if not osp.isfile(filename): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) elif filename.startswith('mmcls://'): model_urls = get_mmcls_models() model_name = filename[8:] checkpoint = load_url_dist(model_urls[model_name]) checkpoint = _process_mmcls_checkpoint(checkpoint) elif filename.startswith(('http://', 'https://')): checkpoint = load_url_dist(filename) elif filename.startswith('pavi://'): model_path = filename[7:] checkpoint = load_pavimodel_dist(model_path, map_location=map_location) elif filename.startswith('s3://'): checkpoint = load_fileclient_dist( filename, backend='ceph', map_location=map_location) else: if not osp.isfile(filename): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) return checkpoint def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None): """Load checkpoint from a file or URI. Args: model (Module): Module to load checkpoint. filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str): Same as :func:`torch.load`. strict (bool): Whether to allow different params for the model and checkpoint. logger (:mod:`logging.Logger` or None): The logger for error message. Returns: dict or OrderedDict: The loaded checkpoint. """ checkpoint = _load_checkpoint(filename, map_location) # OrderedDict is a subclass of dict if not isinstance(checkpoint, dict): raise RuntimeError( f'No state_dict found in checkpoint file {filename}') # get state_dict from checkpoint if 'state_dict' in checkpoint: state_dict = checkpoint['state_dict'] elif 'state_dict_ema' in checkpoint: state_dict = checkpoint['state_dict_ema'] elif 'model' in checkpoint: state_dict = checkpoint['model'] else: state_dict = checkpoint # strip prefix of state_dict if list(state_dict.keys())[0].startswith('module.'): state_dict = {k[7:]: v for k, v in state_dict.items()} # for MoBY, load model of online branch if sorted(list(state_dict.keys()))[0].startswith('encoder'): state_dict = {k.replace('encoder.', ''): v for k, v in state_dict.items() if k.startswith('encoder.')} # reshape absolute position embedding if state_dict.get('absolute_pos_embed') is not None: absolute_pos_embed = state_dict['absolute_pos_embed'] N1, L, C1 = absolute_pos_embed.size() N2, C2, H, W = model.absolute_pos_embed.size() if N1 != N2 or C1 != C2 or L != H*W: logger.warning("Error in loading absolute_pos_embed, pass") else: state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2) # interpolate position bias table if needed relative_position_bias_table_keys = [k for k in state_dict.keys() if "relative_position_bias_table" in k] for table_key in relative_position_bias_table_keys: table_pretrained = state_dict[table_key] table_current = model.state_dict()[table_key] L1, nH1 = table_pretrained.size() L2, nH2 = table_current.size() if nH1 != nH2: logger.warning(f"Error in loading {table_key}, pass") else: if L1 != L2: S1 = int(L1 ** 0.5) S2 = int(L2 ** 0.5) table_pretrained_resized = F.interpolate( table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2), mode='bicubic') state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0) # load state_dict load_state_dict(model, state_dict, strict, logger) return checkpoint def weights_to_cpu(state_dict): """Copy a model state_dict to cpu. Args: state_dict (OrderedDict): Model weights on GPU. Returns: OrderedDict: Model weights on GPU. """ state_dict_cpu = OrderedDict() for key, val in state_dict.items(): state_dict_cpu[key] = val.cpu() return state_dict_cpu def _save_to_state_dict(module, destination, prefix, keep_vars): """Saves module state to `destination` dictionary. This method is modified from :meth:`torch.nn.Module._save_to_state_dict`. Args: module (nn.Module): The module to generate state_dict. destination (dict): A dict where state will be stored. prefix (str): The prefix for parameters and buffers used in this module. """ for name, param in module._parameters.items(): if param is not None: destination[prefix + name] = param if keep_vars else param.detach() for name, buf in module._buffers.items(): # remove check of _non_persistent_buffers_set to allow nn.BatchNorm2d if buf is not None: destination[prefix + name] = buf if keep_vars else buf.detach() def get_state_dict(module, destination=None, prefix='', keep_vars=False): """Returns a dictionary containing a whole state of the module. Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. This method is modified from :meth:`torch.nn.Module.state_dict` to recursively check parallel module in case that the model has a complicated structure, e.g., nn.Module(nn.Module(DDP)). Args: module (nn.Module): The module to generate state_dict. destination (OrderedDict): Returned dict for the state of the module. prefix (str): Prefix of the key. keep_vars (bool): Whether to keep the variable property of the parameters. Default: False. Returns: dict: A dictionary containing a whole state of the module. """ # recursively check parallel module in case that the model has a # complicated structure, e.g., nn.Module(nn.Module(DDP)) if is_module_wrapper(module): module = module.module # below is the same as torch.nn.Module.state_dict() if destination is None: destination = OrderedDict() destination._metadata = OrderedDict() destination._metadata[prefix[:-1]] = local_metadata = dict( version=module._version) _save_to_state_dict(module, destination, prefix, keep_vars) for name, child in module._modules.items(): if child is not None: get_state_dict( child, destination, prefix + name + '.', keep_vars=keep_vars) for hook in module._state_dict_hooks.values(): hook_result = hook(module, destination, prefix, local_metadata) if hook_result is not None: destination = hook_result return destination def save_checkpoint(model, filename, optimizer=None, meta=None): """Save checkpoint to file. The checkpoint will have 3 fields: ``meta``, ``state_dict`` and ``optimizer``. By default ``meta`` will contain version and time info. Args: model (Module): Module whose params are to be saved. filename (str): Checkpoint filename. optimizer (:obj:`Optimizer`, optional): Optimizer to be saved. meta (dict, optional): Metadata to be saved in checkpoint. """ if meta is None: meta = {} elif not isinstance(meta, dict): raise TypeError(f'meta must be a dict or None, but got {type(meta)}') meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) if is_module_wrapper(model): model = model.module if hasattr(model, 'CLASSES') and model.CLASSES is not None: # save class name to the meta meta.update(CLASSES=model.CLASSES) checkpoint = { 'meta': meta, 'state_dict': weights_to_cpu(get_state_dict(model)) } # save optimizer state dict in the checkpoint if isinstance(optimizer, Optimizer): checkpoint['optimizer'] = optimizer.state_dict() elif isinstance(optimizer, dict): checkpoint['optimizer'] = {} for name, optim in optimizer.items(): checkpoint['optimizer'][name] = optim.state_dict() if filename.startswith('pavi://'): try: from pavi import modelcloud from pavi.exception import NodeNotFoundError except ImportError: raise ImportError( 'Please install pavi to load checkpoint from modelcloud.') model_path = filename[7:] root = modelcloud.Folder() model_dir, model_name = osp.split(model_path) try: model = modelcloud.get(model_dir) except NodeNotFoundError: model = root.create_training_model(model_dir) with TemporaryDirectory() as tmp_dir: checkpoint_file = osp.join(tmp_dir, model_name) with open(checkpoint_file, 'wb') as f: torch.save(checkpoint, f) f.flush() model.create_file(checkpoint_file, name=model_name) else: mmcv.mkdir_or_exist(osp.dirname(filename)) # immediately flush buffer with open(filename, 'wb') as f: torch.save(checkpoint, f) f.flush()
19,055
36.884692
110
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/segmentation/configs/_base/upernet_cswin.py
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained=None, backbone=dict( type='CSWin', embed_dim=64, patch_size=4, depth=[1, 2, 21, 1], num_heads=[2,4,8,16], split_size=[1,2,7,7], mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1), decode_head=dict( type='UPerHead', in_channels=[96, 192, 384, 768], in_index=[0, 1, 2, 3], pool_scales=(1, 2, 3, 6), channels=512, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=dict( type='FCNHead', in_channels=384, in_index=2, channels=256, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)), # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole'))
1,303
26.744681
74
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/segmentation/configs/cswin/upernet_cswin_base.py
_base_ = [ '../_base_/models/upernet_cswin.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] model = dict( backbone=dict( type='CSWin', embed_dim=96, depth=[2,4,32,2], num_heads=[4,8,16,32], split_size=[1,2,7,7], drop_path_rate=0.6, use_chk=False, ), decode_head=dict( in_channels=[96,192,384,768], num_classes=150 ), auxiliary_head=dict( in_channels=384, num_classes=150 )) # AdamW optimizer, no weight decay for position embedding & layer norm in backbone optimizer = dict(_delete_=True, type='AdamW', lr=0.00006, betas=(0.9, 0.999), weight_decay=0.01, paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.), 'relative_position_bias_table': dict(decay_mult=0.), 'norm': dict(decay_mult=0.)})) lr_config = dict(_delete_=True, policy='poly', warmup='linear', warmup_iters=1500, warmup_ratio=1e-6, power=1.0, min_lr=0.0, by_epoch=False) data=dict(samples_per_gpu=2)
1,251
31.947368
101
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/segmentation/configs/cswin/upernet_cswin_tiny.py
_base_ = [ '../_base_/models/upernet_cswin.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] model = dict( backbone=dict( type='CSWin', embed_dim=64, depth=[1,2,21,1], num_heads=[2,4,8,16], split_size=[1,2,7,7], drop_path_rate=0.3, use_chk=False, ), decode_head=dict( in_channels=[64,128,256,512], num_classes=150 ), auxiliary_head=dict( in_channels=256, num_classes=150 )) # AdamW optimizer, no weight decay for position embedding & layer norm in backbone optimizer = dict(_delete_=True, type='AdamW', lr=0.00006, betas=(0.9, 0.999), weight_decay=0.01, paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.), 'relative_position_bias_table': dict(decay_mult=0.), 'norm': dict(decay_mult=0.)})) lr_config = dict(_delete_=True, policy='poly', warmup='linear', warmup_iters=1500, warmup_ratio=1e-6, power=1.0, min_lr=0.0, by_epoch=False) data=dict(samples_per_gpu=2)
1,250
31.921053
101
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/segmentation/configs/cswin/upernet_cswin_small.py
_base_ = [ '../_base_/models/upernet_cswin.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] model = dict( backbone=dict( type='CSWin', embed_dim=64, depth=[2,4,32,2], num_heads=[2,4,8,16], split_size=[1,2,7,7], drop_path_rate=0.4, use_chk=False, ), decode_head=dict( in_channels=[64,128,256,512], num_classes=150 ), auxiliary_head=dict( in_channels=256, num_classes=150 )) # AdamW optimizer, no weight decay for position embedding & layer norm in backbone optimizer = dict(_delete_=True, type='AdamW', lr=0.00006, betas=(0.9, 0.999), weight_decay=0.01, paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.), 'relative_position_bias_table': dict(decay_mult=0.), 'norm': dict(decay_mult=0.)})) lr_config = dict(_delete_=True, policy='poly', warmup='linear', warmup_iters=1500, warmup_ratio=1e-6, power=1.0, min_lr=0.0, by_epoch=False) data=dict(samples_per_gpu=2)
1,249
32.783784
101
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/models/cswin_boat.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.helpers import load_pretrained from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.registry import register_model from einops.layers.torch import Rearrange import torch.utils.checkpoint as checkpoint import numpy as np import time from einops import rearrange, repeat import math def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'crop_pct': .9, 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'patch_embed.proj', 'classifier': 'head', **kwargs } default_cfgs = { 'cswin_224': _cfg(), 'cswin_384': _cfg( crop_pct=1.0 ), } class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class LePEAttention(nn.Module): def __init__(self, dim, resolution, idx, split_size=7, dim_out=None, num_heads=8, attn_drop=0., proj_drop=0., qk_scale=None): super().__init__() self.dim = dim self.dim_out = dim_out or dim self.resolution = resolution self.split_size = split_size self.num_heads = num_heads head_dim = dim // num_heads # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights self.scale = qk_scale or head_dim ** -0.5 if idx == -1: H_sp, W_sp = self.resolution, self.resolution elif idx == 0: H_sp, W_sp = self.resolution, self.split_size elif idx == 1: W_sp, H_sp = self.resolution, self.split_size else: print ("ERROR MODE", idx) exit(0) self.H_sp = H_sp self.W_sp = W_sp stride = 1 self.get_v = nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1,groups=dim) self.attn_drop = nn.Dropout(attn_drop) def im2cswin(self, x): B, N, C = x.shape H = W = int(np.sqrt(N)) x = x.transpose(-2,-1).contiguous().view(B, C, H, W) x = img2windows(x, self.H_sp, self.W_sp) x = x.reshape(-1, self.H_sp* self.W_sp, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3).contiguous() return x def get_lepe(self, x, func): B, N, C = x.shape H = W = int(np.sqrt(N)) x = x.transpose(-2,-1).contiguous().view(B, C, H, W) H_sp, W_sp = self.H_sp, self.W_sp x = x.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp) x = x.permute(0, 2, 4, 1, 3, 5).contiguous().reshape(-1, C, H_sp, W_sp) ### B', C, H', W' lepe = func(x) ### B', C, H', W' lepe = lepe.reshape(-1, self.num_heads, C // self.num_heads, H_sp * W_sp).permute(0, 1, 3, 2).contiguous() x = x.reshape(-1, self.num_heads, C // self.num_heads, self.H_sp* self.W_sp).permute(0, 1, 3, 2).contiguous() return x, lepe def forward(self, qkv): """ x: B L C """ q,k,v = qkv[0], qkv[1], qkv[2] ### Img2Window H = W = self.resolution B, L, C = q.shape assert L == H * W, "flatten img_tokens has wrong size" q = self.im2cswin(q) k = self.im2cswin(k) v, lepe = self.get_lepe(v, self.get_v) q = q * self.scale attn = (q @ k.transpose(-2, -1)) # B head N C @ B head C N --> B head N N attn = nn.functional.softmax(attn, dim=-1, dtype=attn.dtype) attn = self.attn_drop(attn) x = (attn @ v) + lepe x = x.transpose(1, 2).reshape(-1, self.H_sp* self.W_sp, C) # B head N N @ B head N C ### Window2Img x = windows2img(x, self.H_sp, self.W_sp, H, W).view(B, -1, C) # B H' W' C return x class ContentAttention(nn.Module): def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.): super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.ws = window_size self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.softmax = nn.Softmax(dim=-1) self.get_v = nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1,groups=dim) def forward(self, x, mask=None): #B_, W, H, C = x.shape #x = x.view(B_,W*H,C) B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)# 3, B_, self.num_heads,N,D if True: q_pre = qkv[0].reshape(B_*self.num_heads,N, C // self.num_heads).permute(0,2,1)#qkv_pre[:,0].reshape(b*self.num_heads,qkvhd//3//self.num_heads,hh*ww) ntimes = int(math.log(N//49,2)) q_idx_last = torch.arange(N).cuda().unsqueeze(0).expand(B_*self.num_heads,N) for i in range(ntimes): bh,d,n = q_pre.shape q_pre_new = q_pre.reshape(bh,d,2,n//2) q_avg = q_pre_new.mean(dim=-1)#.reshape(b*self.num_heads,qkvhd//3//self.num_heads,) q_avg = torch.nn.functional.normalize(q_avg,dim=-2) iters = 2 for i in range(iters): q_scores = torch.nn.functional.normalize(q_pre.permute(0,2,1),dim=-1).bmm(q_avg) soft_assign = torch.nn.functional.softmax(q_scores*100, dim=-1).detach() q_avg = q_pre.bmm(soft_assign) q_avg = torch.nn.functional.normalize(q_avg,dim=-2) q_scores = torch.nn.functional.normalize(q_pre.permute(0,2,1),dim=-1).bmm(q_avg).reshape(bh,n,2)#.unsqueeze(2) q_idx = (q_scores[:,:,0]+1)/(q_scores[:,:,1]+1) _,q_idx = torch.sort(q_idx,dim=-1) q_idx_last = q_idx_last.gather(dim=-1,index=q_idx).reshape(bh*2,n//2) q_idx = q_idx.unsqueeze(1).expand(q_pre.size()) q_pre = q_pre.gather(dim=-1,index=q_idx).reshape(bh,d,2,n//2).permute(0,2,1,3).reshape(bh*2,d,n//2) q_idx = q_idx_last.view(B_,self.num_heads,N) _,q_idx_rev = torch.sort(q_idx,dim=-1) q_idx = q_idx.unsqueeze(0).unsqueeze(4).expand(qkv.size()) qkv_pre = qkv.gather(dim=-2,index=q_idx) q, k, v = rearrange(qkv_pre, 'qkv b h (nw ws) c -> qkv (b nw) h ws c', ws=49) k = k.view(B_*((N//49))//2,2,self.num_heads,49,-1) k_over1 = k[:,1,:,:20].unsqueeze(1)#.expand(-1,2,-1,-1,-1) k_over2 = k[:,0,:,29:].unsqueeze(1)#.expand(-1,2,-1,-1,-1) k_over = torch.cat([k_over1,k_over2],1) k = torch.cat([k,k_over],3).contiguous().view(B_*((N//49)),self.num_heads,49+20,-1) v = v.view(B_*((N//49))//2,2,self.num_heads,49,-1) v_over1 = v[:,1,:,:20].unsqueeze(1)#.expand(-1,2,-1,-1,-1) v_over2 = v[:,0,:,29:].unsqueeze(1)#.expand(-1,2,-1,-1,-1) v_over = torch.cat([v_over1,v_over2],1) v = torch.cat([v,v_over],3).contiguous().view(B_*((N//49)),self.num_heads,49+20,-1) #v = rearrange(v[:,:,:49,:], '(b nw) h ws d -> b h d (nw ws)', h=self.num_heads, b=B_) #W = int(math.sqrt(N)) attn = (q @ k.transpose(-2, -1))*self.scale attn = self.softmax(attn) attn = self.attn_drop(attn) out = attn @ v out = rearrange(out, '(b nw) h ws d -> b (h d) nw ws', h=self.num_heads, b=B_) out = out.reshape(B_,self.num_heads,C//self.num_heads,-1) q_idx_rev = q_idx_rev.unsqueeze(2).expand(out.size()) x = out.gather(dim=-1,index=q_idx_rev).reshape(B_,C,N).permute(0,2,1) v = rearrange(v[:,:,:49,:], '(b nw) h ws d -> b h d (nw ws)', h=self.num_heads, b=B_) W = int(math.sqrt(N)) v = v.gather(dim=-1,index=q_idx_rev).reshape(B_,C,W,W) v = self.get_v(v) v = v.reshape(B_,C,N).permute(0,2,1) x = x + v x = self.proj(x) x = self.proj_drop(x) return x class CSWinBlock(nn.Module): def __init__(self, dim, reso, num_heads, split_size=7, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, last_stage=False, content=False): super().__init__() self.dim = dim self.num_heads = num_heads self.patches_resolution = reso self.split_size = split_size self.mlp_ratio = mlp_ratio self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.norm1 = norm_layer(dim) if self.patches_resolution == split_size: last_stage = True if last_stage: self.branch_num = 1 else: self.branch_num = 2 self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(drop) self.content = content if last_stage: self.attns = nn.ModuleList([ LePEAttention( dim, resolution=self.patches_resolution, idx = -1, split_size=split_size, num_heads=num_heads, dim_out=dim, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) for i in range(self.branch_num)]) else: self.attns = nn.ModuleList([ LePEAttention( dim//2, resolution=self.patches_resolution, idx = i, split_size=split_size, num_heads=num_heads//2, dim_out=dim//2, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) for i in range(self.branch_num)]) if self.content: self.content_attn = ContentAttention(dim=dim, window_size=split_size, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qkv_bias, attn_drop=attn_drop, proj_drop=attn_drop) self.norm3 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, out_features=dim, act_layer=act_layer, drop=drop) self.norm2 = norm_layer(dim) def forward(self, x): """ x: B, H*W, C """ H = W = self.patches_resolution B, L, C = x.shape assert L == H * W, "flatten img_tokens has wrong size" img = self.norm1(x) qkv = self.qkv(img).reshape(B, -1, 3, C).permute(2, 0, 1, 3) if self.branch_num == 2: x1 = self.attns[0](qkv[:,:,:,:C//2]) x2 = self.attns[1](qkv[:,:,:,C//2:]) attened_x = torch.cat([x1,x2], dim=2) else: attened_x = self.attns[0](qkv) attened_x = self.proj(attened_x) x = x + self.drop_path(attened_x) if self.content: x = x + self.drop_path(self.content_attn(self.norm3(x))) x = x + self.drop_path(self.mlp(self.norm2(x))) return x def img2windows(img, H_sp, W_sp): """ img: B C H W """ B, C, H, W = img.shape img_reshape = img.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp) img_perm = img_reshape.permute(0, 2, 4, 3, 5, 1).contiguous().reshape(-1, H_sp* W_sp, C) return img_perm def windows2img(img_splits_hw, H_sp, W_sp, H, W): """ img_splits_hw: B' H W C """ B = int(img_splits_hw.shape[0] / (H * W / H_sp / W_sp)) img = img_splits_hw.view(B, H // H_sp, W // W_sp, H_sp, W_sp, -1) img = img.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return img class Merge_Block(nn.Module): def __init__(self, dim, dim_out, norm_layer=nn.LayerNorm): super().__init__() self.conv = nn.Conv2d(dim, dim_out, 3, 2, 1) self.norm = norm_layer(dim_out) def forward(self, x): B, new_HW, C = x.shape H = W = int(np.sqrt(new_HW)) x = x.transpose(-2, -1).contiguous().view(B, C, H, W) x = self.conv(x) B, C = x.shape[:2] x = x.view(B, C, -1).transpose(-2, -1).contiguous() x = self.norm(x) return x class CSWinTransformer(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=96, depth=[2,2,6,2], split_size = [3,5,7], num_heads=12, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., hybrid_backbone=None, norm_layer=nn.LayerNorm, use_chk=False): super().__init__() self.use_chk = use_chk self.num_classes = num_classes self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models heads=num_heads self.stage1_conv_embed = nn.Sequential( nn.Conv2d(in_chans, embed_dim, 7, 4, 2), Rearrange('b c h w -> b (h w) c', h = img_size//4, w = img_size//4), nn.LayerNorm(embed_dim) ) curr_dim = embed_dim dpr = [x.item() for x in torch.linspace(0, drop_path_rate, np.sum(depth))] # stochastic depth decay rule self.stage1 = nn.ModuleList([ CSWinBlock( dim=curr_dim, num_heads=heads[0], reso=img_size//4, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[0], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, content=(i%2==0)) for i in range(depth[0])]) self.merge1 = Merge_Block(curr_dim, curr_dim*2) curr_dim = curr_dim*2 self.stage2 = nn.ModuleList( [CSWinBlock( dim=curr_dim, num_heads=heads[1], reso=img_size//8, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[1], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:1])+i], norm_layer=norm_layer,content=(i%2==0)) for i in range(depth[1])]) self.merge2 = Merge_Block(curr_dim, curr_dim*2) curr_dim = curr_dim*2 temp_stage3 = [] temp_stage3.extend( [CSWinBlock( dim=curr_dim, num_heads=heads[2], reso=img_size//16, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[2], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:2])+i], norm_layer=norm_layer,content=(i%2==0)) for i in range(depth[2])]) self.stage3 = nn.ModuleList(temp_stage3) self.merge3 = Merge_Block(curr_dim, curr_dim*2) curr_dim = curr_dim*2 self.stage4 = nn.ModuleList( [CSWinBlock( dim=curr_dim, num_heads=heads[3], reso=img_size//32, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[-1], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:-1])+i], norm_layer=norm_layer, last_stage=True,content=(i%2==0)) for i in range(depth[-1])]) self.norm = norm_layer(curr_dim) # Classifier head self.head = nn.Linear(curr_dim, num_classes) if num_classes > 0 else nn.Identity() trunc_normal_(self.head.weight, std=0.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d)): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token'} def get_classifier(self): return self.head def reset_classifier(self, num_classes, global_pool=''): if self.num_classes != num_classes: print ('reset head to', num_classes) self.num_classes = num_classes self.head = nn.Linear(self.out_dim, num_classes) if num_classes > 0 else nn.Identity() self.head = self.head.cuda() trunc_normal_(self.head.weight, std=.02) if self.head.bias is not None: nn.init.constant_(self.head.bias, 0) def forward_features(self, x): B = x.shape[0] x = self.stage1_conv_embed(x) for blk in self.stage1: if self.use_chk: x = checkpoint.checkpoint(blk, x) else: x = blk(x) for pre, blocks in zip([self.merge1, self.merge2, self.merge3], [self.stage2, self.stage3, self.stage4]): x = pre(x) for blk in blocks: if self.use_chk: x = checkpoint.checkpoint(blk, x) else: x = blk(x) x = self.norm(x) return torch.mean(x, dim=1) def forward(self, x): x = self.forward_features(x) x = self.head(x) return x def _conv_filter(state_dict, patch_size=16): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: v = v.reshape((v.shape[0], 3, patch_size, patch_size)) out_dict[k] = v return out_dict ### 224 models @register_model def CSWin_64_12211_tiny_224(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=64, depth=[1,2,21,1], split_size=[1,2,7,7], num_heads=[2,4,8,16], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_224'] return model @register_model def CSWin_64_24322_small_224(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=64, depth=[2,4,32,2], split_size=[1,2,7,7], num_heads=[2,4,8,16], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_224'] return model @register_model def CSWin_96_24322_base_224(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=96, depth=[2,4,32,2], split_size=[1,2,7,7], num_heads=[4,8,16,32], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_224'] return model @register_model def CSWin_144_24322_large_224(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=144, depth=[2,4,32,2], split_size=[1,2,7,7], num_heads=[6,12,24,24], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_224'] return model ### 384 models @register_model def CSWin_96_24322_base_384(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=96, depth=[2,4,32,2], split_size=[1,2,12,12], num_heads=[4,8,16,32], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_384'] return model @register_model def CSWin_144_24322_large_384(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=144, depth=[2,4,32,2], split_size=[1,2,12,12], num_heads=[6,12,24,24], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_384'] return model
20,463
38.353846
183
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/models/__init__.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ from .cswin_boat import *
235
25.222222
44
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/main.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import time import random import argparse import datetime import numpy as np import torch import torch.backends.cudnn as cudnn import torch.distributed as dist from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from timm.utils import accuracy, AverageMeter from config import get_config from models import build_model from data import build_loader from lr_scheduler import build_scheduler from optimizer import build_optimizer from logger import create_logger from utils import load_checkpoint, load_pretrained, save_checkpoint, get_grad_norm, auto_resume_helper, reduce_tensor try: # noinspection PyUnresolvedReferences from apex import amp except ImportError: amp = None def parse_option(): parser = argparse.ArgumentParser('Swin Transformer training and evaluation script', add_help=False) parser.add_argument('--cfg', type=str, required=True, metavar="FILE", help='path to config file', ) parser.add_argument( "--opts", help="Modify config options by adding 'KEY VALUE' pairs. ", default=None, nargs='+', ) # easy config modification parser.add_argument('--batch-size', type=int, help="batch size for single GPU") parser.add_argument('--data-path', type=str, help='path to dataset') parser.add_argument('--zip', action='store_true', help='use zipped dataset instead of folder dataset') parser.add_argument('--cache-mode', type=str, default='part', choices=['no', 'full', 'part'], help='no: no cache, ' 'full: cache all data, ' 'part: sharding the dataset into nonoverlapping pieces and only cache one piece') parser.add_argument('--pretrained', help='pretrained weight from checkpoint, could be imagenet22k pretrained weight') parser.add_argument('--resume', help='resume from checkpoint') parser.add_argument('--accumulation-steps', type=int, help="gradient accumulation steps") parser.add_argument('--use-checkpoint', action='store_true', help="whether to use gradient checkpointing to save memory") parser.add_argument('--amp-opt-level', type=str, default='O1', choices=['O0', 'O1', 'O2'], help='mixed precision opt level, if O0, no amp is used') parser.add_argument('--output', default='output', type=str, metavar='PATH', help='root of output folder, the full path is <output>/<model_name>/<tag> (default: output)') parser.add_argument('--tag', help='tag of experiment') parser.add_argument('--eval', action='store_true', help='Perform evaluation only') parser.add_argument('--throughput', action='store_true', help='Test throughput only') # distributed training parser.add_argument("--local_rank", type=int, required=True, help='local rank for DistributedDataParallel') args, unparsed = parser.parse_known_args() config = get_config(args) return args, config def main(config): dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn = build_loader(config) logger.info(f"Creating model:{config.MODEL.TYPE}/{config.MODEL.NAME}") model = build_model(config) model.cuda() logger.info(str(model)) optimizer = build_optimizer(config, model) if config.AMP_OPT_LEVEL != "O0": model, optimizer = amp.initialize(model, optimizer, opt_level=config.AMP_OPT_LEVEL) model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[config.LOCAL_RANK], broadcast_buffers=False) model_without_ddp = model.module n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) logger.info(f"number of params: {n_parameters}") if hasattr(model_without_ddp, 'flops'): flops = model_without_ddp.flops() logger.info(f"number of GFLOPs: {flops / 1e9}") lr_scheduler = build_scheduler(config, optimizer, len(data_loader_train)) if config.AUG.MIXUP > 0.: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif config.MODEL.LABEL_SMOOTHING > 0.: criterion = LabelSmoothingCrossEntropy(smoothing=config.MODEL.LABEL_SMOOTHING) else: criterion = torch.nn.CrossEntropyLoss() max_accuracy = 0.0 if config.TRAIN.AUTO_RESUME: resume_file = auto_resume_helper(config.OUTPUT) if resume_file: if config.MODEL.RESUME: logger.warning(f"auto-resume changing resume file from {config.MODEL.RESUME} to {resume_file}") config.defrost() config.MODEL.RESUME = resume_file config.freeze() logger.info(f'auto resuming from {resume_file}') else: logger.info(f'no checkpoint found in {config.OUTPUT}, ignoring auto resume') if config.MODEL.RESUME: max_accuracy = load_checkpoint(config, model_without_ddp, optimizer, lr_scheduler, logger) acc1, acc5, loss = validate(config, data_loader_val, model) logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") if config.EVAL_MODE: return if config.MODEL.PRETRAINED and (not config.MODEL.RESUME): load_pretrained(config, model_without_ddp, logger) acc1, acc5, loss = validate(config, data_loader_val, model) logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") if config.THROUGHPUT_MODE: throughput(data_loader_val, model, logger) return logger.info("Start training") start_time = time.time() for epoch in range(config.TRAIN.START_EPOCH, config.TRAIN.EPOCHS): data_loader_train.sampler.set_epoch(epoch) train_one_epoch(config, model, criterion, data_loader_train, optimizer, epoch, mixup_fn, lr_scheduler) if dist.get_rank() == 0 and (epoch % config.SAVE_FREQ == 0 or epoch == (config.TRAIN.EPOCHS - 1)): save_checkpoint(config, epoch, model_without_ddp, max_accuracy, optimizer, lr_scheduler, logger) acc1, acc5, loss = validate(config, data_loader_val, model) logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") max_accuracy = max(max_accuracy, acc1) logger.info(f'Max accuracy: {max_accuracy:.2f}%') total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) logger.info('Training time {}'.format(total_time_str)) def train_one_epoch(config, model, criterion, data_loader, optimizer, epoch, mixup_fn, lr_scheduler): model.train() optimizer.zero_grad() num_steps = len(data_loader) batch_time = AverageMeter() loss_meter = AverageMeter() norm_meter = AverageMeter() start = time.time() end = time.time() for idx, (samples, targets) in enumerate(data_loader): samples = samples.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) if mixup_fn is not None: samples, targets = mixup_fn(samples, targets) outputs = model(samples) if config.TRAIN.ACCUMULATION_STEPS > 1: loss = criterion(outputs, targets) loss = loss / config.TRAIN.ACCUMULATION_STEPS if config.AMP_OPT_LEVEL != "O0": with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() if config.TRAIN.CLIP_GRAD: grad_norm = torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), config.TRAIN.CLIP_GRAD) else: grad_norm = get_grad_norm(amp.master_params(optimizer)) else: loss.backward() if config.TRAIN.CLIP_GRAD: grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config.TRAIN.CLIP_GRAD) else: grad_norm = get_grad_norm(model.parameters()) if (idx + 1) % config.TRAIN.ACCUMULATION_STEPS == 0: optimizer.step() optimizer.zero_grad() lr_scheduler.step_update(epoch * num_steps + idx) else: loss = criterion(outputs, targets) optimizer.zero_grad() if config.AMP_OPT_LEVEL != "O0": with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() if config.TRAIN.CLIP_GRAD: grad_norm = torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), config.TRAIN.CLIP_GRAD) else: grad_norm = get_grad_norm(amp.master_params(optimizer)) else: loss.backward() if config.TRAIN.CLIP_GRAD: grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config.TRAIN.CLIP_GRAD) else: grad_norm = get_grad_norm(model.parameters()) optimizer.step() lr_scheduler.step_update(epoch * num_steps + idx) torch.cuda.synchronize() loss_meter.update(loss.item(), targets.size(0)) norm_meter.update(grad_norm) batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: lr = optimizer.param_groups[0]['lr'] memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) etas = batch_time.avg * (num_steps - idx) logger.info( f'Train: [{epoch}/{config.TRAIN.EPOCHS}][{idx}/{num_steps}]\t' f'eta {datetime.timedelta(seconds=int(etas))} lr {lr:.6f}\t' f'time {batch_time.val:.4f} ({batch_time.avg:.4f})\t' f'loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' f'grad_norm {norm_meter.val:.4f} ({norm_meter.avg:.4f})\t' f'mem {memory_used:.0f}MB') epoch_time = time.time() - start logger.info(f"EPOCH {epoch} training takes {datetime.timedelta(seconds=int(epoch_time))}") @torch.no_grad() def validate(config, data_loader, model): criterion = torch.nn.CrossEntropyLoss() model.eval() batch_time = AverageMeter() loss_meter = AverageMeter() acc1_meter = AverageMeter() acc5_meter = AverageMeter() end = time.time() for idx, (images, target) in enumerate(data_loader): images = images.cuda(non_blocking=True) target = target.cuda(non_blocking=True) # compute output output = model(images) # measure accuracy and record loss loss = criterion(output, target) acc1, acc5 = accuracy(output, target, topk=(1, 5)) acc1 = reduce_tensor(acc1) acc5 = reduce_tensor(acc5) loss = reduce_tensor(loss) loss_meter.update(loss.item(), target.size(0)) acc1_meter.update(acc1.item(), target.size(0)) acc5_meter.update(acc5.item(), target.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) logger.info( f'Test: [{idx}/{len(data_loader)}]\t' f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' f'Loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' f'Acc@1 {acc1_meter.val:.3f} ({acc1_meter.avg:.3f})\t' f'Acc@5 {acc5_meter.val:.3f} ({acc5_meter.avg:.3f})\t' f'Mem {memory_used:.0f}MB') logger.info(f' * Acc@1 {acc1_meter.avg:.3f} Acc@5 {acc5_meter.avg:.3f}') return acc1_meter.avg, acc5_meter.avg, loss_meter.avg @torch.no_grad() def throughput(data_loader, model, logger): model.eval() for idx, (images, _) in enumerate(data_loader): images = images.cuda(non_blocking=True) batch_size = images.shape[0] for i in range(50): model(images) torch.cuda.synchronize() logger.info(f"throughput averaged with 30 times") tic1 = time.time() for i in range(30): model(images) torch.cuda.synchronize() tic2 = time.time() logger.info(f"batch_size {batch_size} throughput {30 * batch_size / (tic2 - tic1)}") return if __name__ == '__main__': _, config = parse_option() if config.AMP_OPT_LEVEL != "O0": assert amp is not None, "amp not installed!" if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: rank = int(os.environ["RANK"]) world_size = int(os.environ['WORLD_SIZE']) print(f"RANK and WORLD_SIZE in environ: {rank}/{world_size}") else: rank = -1 world_size = -1 torch.cuda.set_device(config.LOCAL_RANK) torch.distributed.init_process_group(backend='nccl', init_method='env://', world_size=world_size, rank=rank) torch.distributed.barrier() seed = config.SEED + dist.get_rank() torch.manual_seed(seed) torch.cuda.manual_seed(seed) np.random.seed(seed) random.seed(seed) cudnn.benchmark = True # linear scale the learning rate according to total batch size, may not be optimal linear_scaled_lr = config.TRAIN.BASE_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 linear_scaled_warmup_lr = config.TRAIN.WARMUP_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 linear_scaled_min_lr = config.TRAIN.MIN_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 # gradient accumulation also need to scale the learning rate if config.TRAIN.ACCUMULATION_STEPS > 1: linear_scaled_lr = linear_scaled_lr * config.TRAIN.ACCUMULATION_STEPS linear_scaled_warmup_lr = linear_scaled_warmup_lr * config.TRAIN.ACCUMULATION_STEPS linear_scaled_min_lr = linear_scaled_min_lr * config.TRAIN.ACCUMULATION_STEPS config.defrost() config.TRAIN.BASE_LR = linear_scaled_lr config.TRAIN.WARMUP_LR = linear_scaled_warmup_lr config.TRAIN.MIN_LR = linear_scaled_min_lr config.freeze() os.makedirs(config.OUTPUT, exist_ok=True) logger = create_logger(output_dir=config.OUTPUT, dist_rank=dist.get_rank(), name=f"{config.MODEL.NAME}") if dist.get_rank() == 0: path = os.path.join(config.OUTPUT, "config.json") with open(path, "w") as f: f.write(config.dump()) logger.info(f"Full config saved to {path}") # print config logger.info(config.dump()) main(config)
14,809
40.368715
117
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/lr_scheduler.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import torch from timm.scheduler.cosine_lr import CosineLRScheduler from timm.scheduler.step_lr import StepLRScheduler from timm.scheduler.scheduler import Scheduler def build_scheduler(config, optimizer, n_iter_per_epoch): num_steps = int(config.TRAIN.EPOCHS * n_iter_per_epoch) warmup_steps = int(config.TRAIN.WARMUP_EPOCHS * n_iter_per_epoch) decay_steps = int(config.TRAIN.LR_SCHEDULER.DECAY_EPOCHS * n_iter_per_epoch) lr_scheduler = None if config.TRAIN.LR_SCHEDULER.NAME == 'cosine': lr_scheduler = CosineLRScheduler( optimizer, t_initial=num_steps, t_mul=1., lr_min=config.TRAIN.MIN_LR, warmup_lr_init=config.TRAIN.WARMUP_LR, warmup_t=warmup_steps, cycle_limit=1, t_in_epochs=False, ) elif config.TRAIN.LR_SCHEDULER.NAME == 'linear': lr_scheduler = LinearLRScheduler( optimizer, t_initial=num_steps, lr_min_rate=0.01, warmup_lr_init=config.TRAIN.WARMUP_LR, warmup_t=warmup_steps, t_in_epochs=False, ) elif config.TRAIN.LR_SCHEDULER.NAME == 'step': lr_scheduler = StepLRScheduler( optimizer, decay_t=decay_steps, decay_rate=config.TRAIN.LR_SCHEDULER.DECAY_RATE, warmup_lr_init=config.TRAIN.WARMUP_LR, warmup_t=warmup_steps, t_in_epochs=False, ) return lr_scheduler class LinearLRScheduler(Scheduler): def __init__(self, optimizer: torch.optim.Optimizer, t_initial: int, lr_min_rate: float, warmup_t=0, warmup_lr_init=0., t_in_epochs=True, noise_range_t=None, noise_pct=0.67, noise_std=1.0, noise_seed=42, initialize=True, ) -> None: super().__init__( optimizer, param_group_field="lr", noise_range_t=noise_range_t, noise_pct=noise_pct, noise_std=noise_std, noise_seed=noise_seed, initialize=initialize) self.t_initial = t_initial self.lr_min_rate = lr_min_rate self.warmup_t = warmup_t self.warmup_lr_init = warmup_lr_init self.t_in_epochs = t_in_epochs if self.warmup_t: self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in self.base_values] super().update_groups(self.warmup_lr_init) else: self.warmup_steps = [1 for _ in self.base_values] def _get_lr(self, t): if t < self.warmup_t: lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps] else: t = t - self.warmup_t total_t = self.t_initial - self.warmup_t lrs = [v - ((v - v * self.lr_min_rate) * (t / total_t)) for v in self.base_values] return lrs def get_epoch_values(self, epoch: int): if self.t_in_epochs: return self._get_lr(epoch) else: return None def get_update_values(self, num_updates: int): if not self.t_in_epochs: return self._get_lr(num_updates) else: return None
3,547
33.446602
105
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/utils.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import torch import torch.distributed as dist try: # noinspection PyUnresolvedReferences from apex import amp except ImportError: amp = None def load_checkpoint(config, model, optimizer, lr_scheduler, logger): logger.info(f"==============> Resuming form {config.MODEL.RESUME}....................") if config.MODEL.RESUME.startswith('https'): checkpoint = torch.hub.load_state_dict_from_url( config.MODEL.RESUME, map_location='cpu', check_hash=True) else: checkpoint = torch.load(config.MODEL.RESUME, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) logger.info(msg) max_accuracy = 0.0 if not config.EVAL_MODE and 'optimizer' in checkpoint and 'lr_scheduler' in checkpoint and 'epoch' in checkpoint: optimizer.load_state_dict(checkpoint['optimizer']) lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) config.defrost() config.TRAIN.START_EPOCH = checkpoint['epoch'] + 1 config.freeze() if 'amp' in checkpoint and config.AMP_OPT_LEVEL != "O0" and checkpoint['config'].AMP_OPT_LEVEL != "O0": amp.load_state_dict(checkpoint['amp']) logger.info(f"=> loaded successfully '{config.MODEL.RESUME}' (epoch {checkpoint['epoch']})") if 'max_accuracy' in checkpoint: max_accuracy = checkpoint['max_accuracy'] del checkpoint torch.cuda.empty_cache() return max_accuracy def load_pretrained(config, model, logger): logger.info(f"==============> Loading weight {config.MODEL.PRETRAINED} for fine-tuning......") checkpoint = torch.load(config.MODEL.PRETRAINED, map_location='cpu') state_dict = checkpoint['model'] # delete relative_position_index since we always re-init it relative_position_index_keys = [k for k in state_dict.keys() if "relative_position_index" in k] for k in relative_position_index_keys: del state_dict[k] # delete relative_coords_table since we always re-init it relative_position_index_keys = [k for k in state_dict.keys() if "relative_coords_table" in k] for k in relative_position_index_keys: del state_dict[k] # delete attn_mask since we always re-init it attn_mask_keys = [k for k in state_dict.keys() if "attn_mask" in k] for k in attn_mask_keys: del state_dict[k] # bicubic interpolate relative_position_bias_table if not match relative_position_bias_table_keys = [k for k in state_dict.keys() if "relative_position_bias_table" in k] for k in relative_position_bias_table_keys: relative_position_bias_table_pretrained = state_dict[k] relative_position_bias_table_current = model.state_dict()[k] L1, nH1 = relative_position_bias_table_pretrained.size() L2, nH2 = relative_position_bias_table_current.size() if nH1 != nH2: logger.warning(f"Error in loading {k}, passing......") else: if L1 != L2: # bicubic interpolate relative_position_bias_table if not match S1 = int(L1 ** 0.5) S2 = int(L2 ** 0.5) relative_position_bias_table_pretrained_resized = torch.nn.functional.interpolate( relative_position_bias_table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2), mode='bicubic') state_dict[k] = relative_position_bias_table_pretrained_resized.view(nH2, L2).permute(1, 0) # bicubic interpolate absolute_pos_embed if not match absolute_pos_embed_keys = [k for k in state_dict.keys() if "absolute_pos_embed" in k] for k in absolute_pos_embed_keys: # dpe absolute_pos_embed_pretrained = state_dict[k] absolute_pos_embed_current = model.state_dict()[k] _, L1, C1 = absolute_pos_embed_pretrained.size() _, L2, C2 = absolute_pos_embed_current.size() if C1 != C1: logger.warning(f"Error in loading {k}, passing......") else: if L1 != L2: S1 = int(L1 ** 0.5) S2 = int(L2 ** 0.5) absolute_pos_embed_pretrained = absolute_pos_embed_pretrained.reshape(-1, S1, S1, C1) absolute_pos_embed_pretrained = absolute_pos_embed_pretrained.permute(0, 3, 1, 2) absolute_pos_embed_pretrained_resized = torch.nn.functional.interpolate( absolute_pos_embed_pretrained, size=(S2, S2), mode='bicubic') absolute_pos_embed_pretrained_resized = absolute_pos_embed_pretrained_resized.permute(0, 2, 3, 1) absolute_pos_embed_pretrained_resized = absolute_pos_embed_pretrained_resized.flatten(1, 2) state_dict[k] = absolute_pos_embed_pretrained_resized # check classifier, if not match, then re-init classifier to zero head_bias_pretrained = state_dict['head.bias'] Nc1 = head_bias_pretrained.shape[0] Nc2 = model.head.bias.shape[0] if (Nc1 != Nc2): if Nc1 == 21841 and Nc2 == 1000: logger.info("loading ImageNet-22K weight to ImageNet-1K ......") map22kto1k_path = f'data/map22kto1k.txt' with open(map22kto1k_path) as f: map22kto1k = f.readlines() map22kto1k = [int(id22k.strip()) for id22k in map22kto1k] state_dict['head.weight'] = state_dict['head.weight'][map22kto1k, :] state_dict['head.bias'] = state_dict['head.bias'][map22kto1k] else: torch.nn.init.constant_(model.head.bias, 0.) torch.nn.init.constant_(model.head.weight, 0.) del state_dict['head.weight'] del state_dict['head.bias'] logger.warning(f"Error in loading classifier head, re-init classifier head to 0") msg = model.load_state_dict(state_dict, strict=False) logger.warning(msg) logger.info(f"=> loaded successfully '{config.MODEL.PRETRAINED}'") del checkpoint torch.cuda.empty_cache() def save_checkpoint(config, epoch, model, max_accuracy, optimizer, lr_scheduler, logger): save_state = {'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'lr_scheduler': lr_scheduler.state_dict(), 'max_accuracy': max_accuracy, 'epoch': epoch, 'config': config} if config.AMP_OPT_LEVEL != "O0": save_state['amp'] = amp.state_dict() save_path = os.path.join(config.OUTPUT, f'ckpt_epoch_{epoch}.pth') logger.info(f"{save_path} saving......") torch.save(save_state, save_path) logger.info(f"{save_path} saved !!!") def get_grad_norm(parameters, norm_type=2): if isinstance(parameters, torch.Tensor): parameters = [parameters] parameters = list(filter(lambda p: p.grad is not None, parameters)) norm_type = float(norm_type) total_norm = 0 for p in parameters: param_norm = p.grad.data.norm(norm_type) total_norm += param_norm.item() ** norm_type total_norm = total_norm ** (1. / norm_type) return total_norm def auto_resume_helper(output_dir): checkpoints = os.listdir(output_dir) checkpoints = [ckpt for ckpt in checkpoints if ckpt.endswith('pth')] print(f"All checkpoints founded in {output_dir}: {checkpoints}") if len(checkpoints) > 0: latest_checkpoint = max([os.path.join(output_dir, d) for d in checkpoints], key=os.path.getmtime) print(f"The latest checkpoint founded: {latest_checkpoint}") resume_file = latest_checkpoint else: resume_file = None return resume_file def reduce_tensor(tensor): rt = tensor.clone() dist.all_reduce(rt, op=dist.ReduceOp.SUM) rt /= dist.get_world_size() return rt
8,012
42.786885
117
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/logger.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import sys import logging import functools from termcolor import colored @functools.lru_cache() def create_logger(output_dir, dist_rank=0, name=''): # create logger logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.propagate = False # create formatter fmt = '[%(asctime)s %(name)s] (%(filename)s %(lineno)d): %(levelname)s %(message)s' color_fmt = colored('[%(asctime)s %(name)s]', 'green') + \ colored('(%(filename)s %(lineno)d)', 'yellow') + ': %(levelname)s %(message)s' # create console handlers for master process if dist_rank == 0: console_handler = logging.StreamHandler(sys.stdout) console_handler.setLevel(logging.DEBUG) console_handler.setFormatter( logging.Formatter(fmt=color_fmt, datefmt='%Y-%m-%d %H:%M:%S')) logger.addHandler(console_handler) # create file handlers file_handler = logging.FileHandler(os.path.join(output_dir, f'log_rank{dist_rank}.txt'), mode='a') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(fmt=fmt, datefmt='%Y-%m-%d %H:%M:%S')) logger.addHandler(file_handler) return logger
1,451
33.571429
102
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/config.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # --------------------------------------------------------' import os import yaml from yacs.config import CfgNode as CN _C = CN() # Base config files _C.BASE = [''] # ----------------------------------------------------------------------------- # Data settings # ----------------------------------------------------------------------------- _C.DATA = CN() # Batch size for a single GPU, could be overwritten by command line argument _C.DATA.BATCH_SIZE = 128 # Path to dataset, could be overwritten by command line argument _C.DATA.DATA_PATH = '' # Dataset name _C.DATA.DATASET = 'imagenet' # Input image size _C.DATA.IMG_SIZE = 224 # Interpolation to resize image (random, bilinear, bicubic) _C.DATA.INTERPOLATION = 'bicubic' # Use zipped dataset instead of folder dataset # could be overwritten by command line argument _C.DATA.ZIP_MODE = False # Cache Data in Memory, could be overwritten by command line argument _C.DATA.CACHE_MODE = 'part' # Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU. _C.DATA.PIN_MEMORY = True # Number of data loading threads _C.DATA.NUM_WORKERS = 8 # ----------------------------------------------------------------------------- # Model settings # ----------------------------------------------------------------------------- _C.MODEL = CN() # Model type _C.MODEL.TYPE = 'swin' # Model name _C.MODEL.NAME = 'swin_tiny_patch4_window7_224' # Pretrained weight from checkpoint, could be imagenet22k pretrained weight # could be overwritten by command line argument _C.MODEL.PRETRAINED = '' # Checkpoint to resume, could be overwritten by command line argument _C.MODEL.RESUME = '' # Number of classes, overwritten in data preparation _C.MODEL.NUM_CLASSES = 1000 # Dropout rate _C.MODEL.DROP_RATE = 0.0 # Drop path rate _C.MODEL.DROP_PATH_RATE = 0.1 # Label Smoothing _C.MODEL.LABEL_SMOOTHING = 0.1 # Swin Transformer parameters _C.MODEL.SWIN = CN() _C.MODEL.SWIN.PATCH_SIZE = 4 _C.MODEL.SWIN.IN_CHANS = 3 _C.MODEL.SWIN.EMBED_DIM = 96 _C.MODEL.SWIN.DEPTHS = [2, 2, 6, 2] _C.MODEL.SWIN.NUM_HEADS = [3, 6, 12, 24] _C.MODEL.SWIN.WINDOW_SIZE = 7 _C.MODEL.SWIN.MLP_RATIO = 4. _C.MODEL.SWIN.QKV_BIAS = True _C.MODEL.SWIN.QK_SCALE = None _C.MODEL.SWIN.APE = False _C.MODEL.SWIN.PATCH_NORM = True # Swin MLP parameters _C.MODEL.SWIN_MLP = CN() _C.MODEL.SWIN_MLP.PATCH_SIZE = 4 _C.MODEL.SWIN_MLP.IN_CHANS = 3 _C.MODEL.SWIN_MLP.EMBED_DIM = 96 _C.MODEL.SWIN_MLP.DEPTHS = [2, 2, 6, 2] _C.MODEL.SWIN_MLP.NUM_HEADS = [3, 6, 12, 24] _C.MODEL.SWIN_MLP.WINDOW_SIZE = 7 _C.MODEL.SWIN_MLP.MLP_RATIO = 4. _C.MODEL.SWIN_MLP.APE = False _C.MODEL.SWIN_MLP.PATCH_NORM = True # ----------------------------------------------------------------------------- # Training settings # ----------------------------------------------------------------------------- _C.TRAIN = CN() _C.TRAIN.START_EPOCH = 0 _C.TRAIN.EPOCHS = 300 _C.TRAIN.WARMUP_EPOCHS = 20 _C.TRAIN.WEIGHT_DECAY = 0.05 _C.TRAIN.BASE_LR = 5e-4 _C.TRAIN.WARMUP_LR = 5e-7 _C.TRAIN.MIN_LR = 5e-6 # Clip gradient norm _C.TRAIN.CLIP_GRAD = 5.0 # Auto resume from latest checkpoint _C.TRAIN.AUTO_RESUME = True # Gradient accumulation steps # could be overwritten by command line argument _C.TRAIN.ACCUMULATION_STEPS = 0 # Whether to use gradient checkpointing to save memory # could be overwritten by command line argument _C.TRAIN.USE_CHECKPOINT = False # LR scheduler _C.TRAIN.LR_SCHEDULER = CN() _C.TRAIN.LR_SCHEDULER.NAME = 'cosine' # Epoch interval to decay LR, used in StepLRScheduler _C.TRAIN.LR_SCHEDULER.DECAY_EPOCHS = 30 # LR decay rate, used in StepLRScheduler _C.TRAIN.LR_SCHEDULER.DECAY_RATE = 0.1 # Optimizer _C.TRAIN.OPTIMIZER = CN() _C.TRAIN.OPTIMIZER.NAME = 'adamw' # Optimizer Epsilon _C.TRAIN.OPTIMIZER.EPS = 1e-8 # Optimizer Betas _C.TRAIN.OPTIMIZER.BETAS = (0.9, 0.999) # SGD momentum _C.TRAIN.OPTIMIZER.MOMENTUM = 0.9 # ----------------------------------------------------------------------------- # Augmentation settings # ----------------------------------------------------------------------------- _C.AUG = CN() # Color jitter factor _C.AUG.COLOR_JITTER = 0.4 # Use AutoAugment policy. "v0" or "original" _C.AUG.AUTO_AUGMENT = 'rand-m9-mstd0.5-inc1' # Random erase prob _C.AUG.REPROB = 0.25 # Random erase mode _C.AUG.REMODE = 'pixel' # Random erase count _C.AUG.RECOUNT = 1 # Mixup alpha, mixup enabled if > 0 _C.AUG.MIXUP = 0.8 # Cutmix alpha, cutmix enabled if > 0 _C.AUG.CUTMIX = 1.0 # Cutmix min/max ratio, overrides alpha and enables cutmix if set _C.AUG.CUTMIX_MINMAX = None # Probability of performing mixup or cutmix when either/both is enabled _C.AUG.MIXUP_PROB = 1.0 # Probability of switching to cutmix when both mixup and cutmix enabled _C.AUG.MIXUP_SWITCH_PROB = 0.5 # How to apply mixup/cutmix params. Per "batch", "pair", or "elem" _C.AUG.MIXUP_MODE = 'batch' # ----------------------------------------------------------------------------- # Testing settings # ----------------------------------------------------------------------------- _C.TEST = CN() # Whether to use center crop when testing _C.TEST.CROP = True # Whether to use SequentialSampler as validation sampler _C.TEST.SEQUENTIAL = False # ----------------------------------------------------------------------------- # Misc # ----------------------------------------------------------------------------- # Mixed precision opt level, if O0, no amp is used ('O0', 'O1', 'O2') # overwritten by command line argument _C.AMP_OPT_LEVEL = '' # Path to output folder, overwritten by command line argument _C.OUTPUT = '' # Tag of experiment, overwritten by command line argument _C.TAG = 'default' # Frequency to save checkpoint _C.SAVE_FREQ = 1 # Frequency to logging info _C.PRINT_FREQ = 10 # Fixed random seed _C.SEED = 0 # Perform evaluation only, overwritten by command line argument _C.EVAL_MODE = False # Test throughput only, overwritten by command line argument _C.THROUGHPUT_MODE = False # local rank for DistributedDataParallel, given by command line argument _C.LOCAL_RANK = 0 def _update_config_from_file(config, cfg_file): config.defrost() with open(cfg_file, 'r') as f: yaml_cfg = yaml.load(f, Loader=yaml.FullLoader) for cfg in yaml_cfg.setdefault('BASE', ['']): if cfg: _update_config_from_file( config, os.path.join(os.path.dirname(cfg_file), cfg) ) print('=> merge config from {}'.format(cfg_file)) config.merge_from_file(cfg_file) config.freeze() def update_config(config, args): _update_config_from_file(config, args.cfg) config.defrost() if args.opts: config.merge_from_list(args.opts) # merge from specific arguments if args.batch_size: config.DATA.BATCH_SIZE = args.batch_size if args.data_path: config.DATA.DATA_PATH = args.data_path if args.zip: config.DATA.ZIP_MODE = True if args.cache_mode: config.DATA.CACHE_MODE = args.cache_mode if args.pretrained: config.MODEL.PRETRAINED = args.pretrained if args.resume: config.MODEL.RESUME = args.resume if args.accumulation_steps: config.TRAIN.ACCUMULATION_STEPS = args.accumulation_steps if args.use_checkpoint: config.TRAIN.USE_CHECKPOINT = True if args.amp_opt_level: config.AMP_OPT_LEVEL = args.amp_opt_level if args.output: config.OUTPUT = args.output if args.tag: config.TAG = args.tag if args.eval: config.EVAL_MODE = True if args.throughput: config.THROUGHPUT_MODE = True # set local rank for distributed training config.LOCAL_RANK = args.local_rank # output folder config.OUTPUT = os.path.join(config.OUTPUT, config.MODEL.NAME, config.TAG) config.freeze() def get_config(args): """Get a yacs CfgNode object with default values.""" # Return a clone so that the defaults will not be altered # This is for the "local variable" use pattern config = _C.clone() update_config(config, args) return config
8,169
30.914063
79
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/optimizer.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- from torch import optim as optim def build_optimizer(config, model): """ Build optimizer, set weight decay of normalization to 0 by default. """ skip = {} skip_keywords = {} if hasattr(model, 'no_weight_decay'): skip = model.no_weight_decay() if hasattr(model, 'no_weight_decay_keywords'): skip_keywords = model.no_weight_decay_keywords() parameters = set_weight_decay(model, skip, skip_keywords) opt_lower = config.TRAIN.OPTIMIZER.NAME.lower() optimizer = None if opt_lower == 'sgd': optimizer = optim.SGD(parameters, momentum=config.TRAIN.OPTIMIZER.MOMENTUM, nesterov=True, lr=config.TRAIN.BASE_LR, weight_decay=config.TRAIN.WEIGHT_DECAY) elif opt_lower == 'adamw': optimizer = optim.AdamW(parameters, eps=config.TRAIN.OPTIMIZER.EPS, betas=config.TRAIN.OPTIMIZER.BETAS, lr=config.TRAIN.BASE_LR, weight_decay=config.TRAIN.WEIGHT_DECAY) return optimizer def set_weight_decay(model, skip_list=(), skip_keywords=()): has_decay = [] no_decay = [] for name, param in model.named_parameters(): if not param.requires_grad: continue # frozen weights if len(param.shape) == 1 or name.endswith(".bias") or (name in skip_list) or \ check_keywords_in_name(name, skip_keywords): no_decay.append(param) # print(f"{name} has no weight decay") else: has_decay.append(param) return [{'params': has_decay}, {'params': no_decay, 'weight_decay': 0.}] def check_keywords_in_name(name, keywords=()): isin = False for keyword in keywords: if keyword in name: isin = True return isin
2,013
33.724138
111
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/models/boat_swin_transformer.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import torch import torch.nn as nn import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, to_2tuple, trunc_normal_ import math from einops import rearrange, repeat class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows def window_reverse(windows, window_size, H, W): """ Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x class ContentAttention(nn.Module): r""" Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window. Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_heads (int): Number of attention heads. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 proj_drop (float, optional): Dropout ratio of output. Default: 0.0 """ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0., kmeans = False): super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.ws = window_size self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.kmeans = kmeans self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.softmax = nn.Softmax(dim=-1) self.get_v = nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1,groups=dim) def forward(self, x, mask=None): """ Args: x: input features with shape of (num_windows*B, N, C) mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None """ B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)# 3, B_, self.num_heads,N,D if True: q_pre = qkv[0].reshape(B_*self.num_heads,N, C // self.num_heads).permute(0,2,1)#qkv_pre[:,0].reshape(b*self.num_heads,qkvhd//3//self.num_heads,hh*ww) ntimes = int(math.log(N//49,2)) q_idx_last = torch.arange(N).cuda().unsqueeze(0).expand(B_*self.num_heads,N) for i in range(ntimes): bh,d,n = q_pre.shape q_pre_new = q_pre.reshape(bh,d,2,n//2) q_avg = q_pre_new.mean(dim=-1)#.reshape(b*self.num_heads,qkvhd//3//self.num_heads,) q_avg = torch.nn.functional.normalize(q_avg,dim=-2) iters = 2 for i in range(iters): q_scores = torch.nn.functional.normalize(q_pre.permute(0,2,1),dim=-1).bmm(q_avg) soft_assign = torch.nn.functional.softmax(q_scores*100, dim=-1).detach() q_avg = q_pre.bmm(soft_assign) q_avg = torch.nn.functional.normalize(q_avg,dim=-2) q_scores = torch.nn.functional.normalize(q_pre.permute(0,2,1),dim=-1).bmm(q_avg).reshape(bh,n,2)#.unsqueeze(2) q_idx = (q_scores[:,:,0]+1)/(q_scores[:,:,1]+1) _,q_idx = torch.sort(q_idx,dim=-1) q_idx_last = q_idx_last.gather(dim=-1,index=q_idx).reshape(bh*2,n//2) q_idx = q_idx.unsqueeze(1).expand(q_pre.size()) q_pre = q_pre.gather(dim=-1,index=q_idx).reshape(bh,d,2,n//2).permute(0,2,1,3).reshape(bh*2,d,n//2) q_idx = q_idx_last.view(B_,self.num_heads,N) _,q_idx_rev = torch.sort(q_idx,dim=-1) q_idx = q_idx.unsqueeze(0).unsqueeze(4).expand(qkv.size()) qkv_pre = qkv.gather(dim=-2,index=q_idx) q, k, v = rearrange(qkv_pre, 'qkv b h (nw ws) c -> qkv (b nw) h ws c', ws=49) k = k.view(B_*((N//49))//2,2,self.num_heads,49,-1) k_over1 = k[:,1,:,:20].unsqueeze(1)#.expand(-1,2,-1,-1,-1) k_over2 = k[:,0,:,29:].unsqueeze(1)#.expand(-1,2,-1,-1,-1) k_over = torch.cat([k_over1,k_over2],1) k = torch.cat([k,k_over],3).contiguous().view(B_*((N//49)),self.num_heads,49+20,-1) v = v.view(B_*((N//49))//2,2,self.num_heads,49,-1) v_over1 = v[:,1,:,:20].unsqueeze(1)#.expand(-1,2,-1,-1,-1) v_over2 = v[:,0,:,29:].unsqueeze(1)#.expand(-1,2,-1,-1,-1) v_over = torch.cat([v_over1,v_over2],1) v = torch.cat([v,v_over],3).contiguous().view(B_*((N//49)),self.num_heads,49+20,-1) attn = (q @ k.transpose(-2, -1))*self.scale attn = self.softmax(attn) attn = self.attn_drop(attn) out = attn @ v if True: out = rearrange(out, '(b nw) h ws d -> b (h d) nw ws', h=self.num_heads, b=B_) v = rearrange(v[:,:,:49,:], '(b nw) h ws d -> b h d (nw ws)', h=self.num_heads, b=B_) W = int(math.sqrt(N)) out = out.reshape(B_,self.num_heads,C//self.num_heads,-1) q_idx_rev = q_idx_rev.unsqueeze(2).expand(out.size()) x = out.gather(dim=-1,index=q_idx_rev).reshape(B_,C,N).permute(0,2,1) v = v.gather(dim=-1,index=q_idx_rev).reshape(B_,C,W,W) v = self.get_v(v) v = v.reshape(B_,C,N).permute(0,2,1) x = x + v x = self.proj(x) x = self.proj_drop(x) return x class WindowAttention(nn.Module): r""" Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window. Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_heads (int): Number of attention heads. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 proj_drop (float, optional): Dropout ratio of output. Default: 0.0 """ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0., kmeans = False): super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.ws = window_size self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.kmeans = kmeans # define a parameter table of relative position bias if True: self.relative_position_bias_table = nn.Parameter( torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH # get pair-wise relative position index for each token inside the window coords_h = torch.arange(self.window_size[0]) coords_w = torch.arange(self.window_size[1]) coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 relative_coords[:, :, 1] += self.window_size[1] - 1 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww self.register_buffer("relative_position_index", relative_position_index) trunc_normal_(self.relative_position_bias_table, std=.02) self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) #trunc_normal_(self.relative_position_bias_table, std=.02) self.softmax = nn.Softmax(dim=-1) def forward(self, x, mask=None): """ Args: x: input features with shape of (num_windows*B, N, C) mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None """ B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) q = q * self.scale attn = (q @ k.transpose(-2, -1)) relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww attn = attn + relative_position_bias.unsqueeze(0) if mask is not None: nW = mask.shape[0] attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) attn = attn.view(-1, self.num_heads, N, N) attn = self.softmax(attn) else: attn = self.softmax(attn) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B_, N, C) x = self.proj(x) x = self.proj_drop(x) return x def extra_repr(self) -> str: return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}' def flops(self, N): # calculate flops for 1 window with token length of N flops = 0 # qkv = self.qkv(x) flops += N * self.dim * 3 * self.dim # attn = (q @ k.transpose(-2, -1)) flops += self.num_heads * N * (self.dim // self.num_heads) * N # x = (attn @ v) flops += self.num_heads * N * N * (self.dim // self.num_heads) # x = self.proj(x) flops += N * self.dim * self.dim return flops class SwinTransformerBlock(nn.Module): r""" Swin Transformer Block. Args: dim (int): Number of input channels. input_resolution (tuple[int]): Input resulotion. num_heads (int): Number of attention heads. window_size (int): Window size. shift_size (int): Shift size for SW-MSA. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. drop (float, optional): Dropout rate. Default: 0.0 attn_drop (float, optional): Attention dropout rate. Default: 0.0 drop_path (float, optional): Stochastic depth rate. Default: 0.0 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.input_resolution = input_resolution self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size self.mlp_ratio = mlp_ratio if min(self.input_resolution) <= self.window_size: # if window size is larger than input resolution, we don't partition windows self.shift_size = 0 self.window_size = min(self.input_resolution) assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" self.norm1 = norm_layer(dim) self.attn = WindowAttention( dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, kmeans=shift_size) if self.shift_size > 0: self.attnC = ContentAttention( dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, kmeans=shift_size) self.norm4 = norm_layer(dim); self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) #self.local = nn.Conv2d(dim, dim, window_size, 1, window_size//2, groups=dim, bias=qkv_bias) #self.norm3 = norm_layer(dim) #self.norm4 = norm_layer(dim) if self.shift_size > 0: # calculate attention mask for SW-MSA H, W = self.input_resolution img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 h_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) w_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) cnt = 0 for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1 mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 mask_windows = mask_windows.view(-1, self.window_size * self.window_size) attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) else: attn_mask = None self.register_buffer("attn_mask", attn_mask) def forward(self, x): H, W = self.input_resolution B, L, C = x.shape assert L == H * W, "input feature has wrong size" shortcut = x x = self.norm1(x) x = x.view(B, H, W, C) # cyclic shift if self.shift_size > 0: shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) #x = self.attn(x.view(B,H*W,C)) else: shifted_x = x if True: # partition windows x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C # W-MSA/SW-MSA attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C # merge windows attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C # reverse cyclic shift if self.shift_size > 0: x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) else: x = shifted_x x = x.view(B, H * W, C) # FFN x = shortcut + self.drop_path(x) if self.shift_size > 0: x = x + self.attnC(self.norm4(x)) b,n,c = x.shape #w = int(math.sqrt(n)) #x = self.norm3(x) #x = x.view(b,w,w,c).permute(0,3,1,2) #x = x + self.local(x) #x = x.permute(0,2,3,1).reshape(b,n,c) x = x + self.drop_path(self.mlp(self.norm2(x))) return x def extra_repr(self) -> str: return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \ f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}" def flops(self): flops = 0 H, W = self.input_resolution # norm1 flops += self.dim * H * W # W-MSA/SW-MSA nW = H * W / self.window_size / self.window_size flops += nW * self.attn.flops(self.window_size * self.window_size) # mlp flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio # norm2 flops += self.dim * H * W return flops class PatchMerging(nn.Module): r""" Patch Merging Layer. Args: input_resolution (tuple[int]): Resolution of input feature. dim (int): Number of input channels. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): super().__init__() self.input_resolution = input_resolution self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim) def forward(self, x): """ x: B, H*W, C """ H, W = self.input_resolution B, L, C = x.shape assert L == H * W, "input feature has wrong size" assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even." x = x.view(B, H, W, C) x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C x = self.norm(x) x = self.reduction(x) return x def extra_repr(self) -> str: return f"input_resolution={self.input_resolution}, dim={self.dim}" def flops(self): H, W = self.input_resolution flops = H * W * self.dim flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim return flops class BasicLayer(nn.Module): """ A basic Swin Transformer layer for one stage. Args: dim (int): Number of input channels. input_resolution (tuple[int]): Input resolution. depth (int): Number of blocks. num_heads (int): Number of attention heads. window_size (int): Local window size. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. drop (float, optional): Dropout rate. Default: 0.0 attn_drop (float, optional): Attention dropout rate. Default: 0.0 drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. """ def __init__(self, dim, input_resolution, depth, num_heads, window_size, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): super().__init__() self.dim = dim self.input_resolution = input_resolution self.depth = depth self.use_checkpoint = use_checkpoint # build blocks self.blocks = nn.ModuleList([ SwinTransformerBlock(dim=dim, input_resolution=input_resolution, num_heads=num_heads, window_size=window_size, shift_size=0 if (i % 2 == 0) else window_size // 2, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer) for i in range(depth)]) # patch merging layer if downsample is not None: self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer) else: self.downsample = None def forward(self, x): for blk in self.blocks: if self.use_checkpoint: x = checkpoint.checkpoint(blk, x) else: x = blk(x) if self.downsample is not None: x = self.downsample(x) return x def extra_repr(self) -> str: return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" def flops(self): flops = 0 for blk in self.blocks: flops += blk.flops() if self.downsample is not None: flops += self.downsample.flops() return flops class PatchEmbed(nn.Module): r""" Image to Patch Embedding Args: img_size (int): Image size. Default: 224. patch_size (int): Patch token size. Default: 4. in_chans (int): Number of input image channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. norm_layer (nn.Module, optional): Normalization layer. Default: None """ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] self.img_size = img_size self.patch_size = patch_size self.patches_resolution = patches_resolution self.num_patches = patches_resolution[0] * patches_resolution[1] self.in_chans = in_chans self.embed_dim = embed_dim self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None def forward(self, x): B, C, H, W = x.shape # FIXME look at relaxing size constraints assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." x = self.proj(x).flatten(2).transpose(1, 2) # B Ph*Pw C if self.norm is not None: x = self.norm(x) return x def flops(self): Ho, Wo = self.patches_resolution flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) if self.norm is not None: flops += Ho * Wo * self.embed_dim return flops class SwinTransformer(nn.Module): r""" Swin Transformer A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - https://arxiv.org/pdf/2103.14030 Args: img_size (int | tuple(int)): Input image size. Default 224 patch_size (int | tuple(int)): Patch size. Default: 4 in_chans (int): Number of input image channels. Default: 3 num_classes (int): Number of classes for classification head. Default: 1000 embed_dim (int): Patch embedding dimension. Default: 96 depths (tuple(int)): Depth of each Swin Transformer layer. num_heads (tuple(int)): Number of attention heads in different layers. window_size (int): Window size. Default: 7 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4 qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None drop_rate (float): Dropout rate. Default: 0 attn_drop_rate (float): Attention dropout rate. Default: 0 drop_path_rate (float): Stochastic depth rate. Default: 0.1 norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. ape (bool): If True, add absolute position embedding to the patch embedding. Default: False patch_norm (bool): If True, add normalization after patch embedding. Default: True use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False """ def __init__(self, img_size=224, patch_size=4, in_chans=3, num_classes=1000, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, norm_layer=nn.LayerNorm, ape=False, patch_norm=True, use_checkpoint=False, **kwargs): super().__init__() self.num_classes = num_classes self.num_layers = len(depths) self.embed_dim = embed_dim self.ape = ape self.patch_norm = patch_norm self.num_features = int(embed_dim * 2 ** (self.num_layers - 1)) self.mlp_ratio = mlp_ratio # split image into non-overlapping patches self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None) num_patches = self.patch_embed.num_patches patches_resolution = self.patch_embed.patches_resolution self.patches_resolution = patches_resolution # absolute position embedding if self.ape: self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim)) trunc_normal_(self.absolute_pos_embed, std=.02) self.pos_drop = nn.Dropout(p=drop_rate) # stochastic depth dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule # build layers self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layer = BasicLayer(dim=int(embed_dim * 2 ** i_layer), input_resolution=(patches_resolution[0] // (2 ** i_layer), patches_resolution[1] // (2 ** i_layer)), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, mlp_ratio=self.mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], norm_layer=norm_layer, downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, use_checkpoint=use_checkpoint) self.layers.append(layer) self.norm = norm_layer(self.num_features) self.avgpool = nn.AdaptiveAvgPool1d(1) self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'absolute_pos_embed'} @torch.jit.ignore def no_weight_decay_keywords(self): return {'relative_position_bias_table'} def forward_features(self, x): x = self.patch_embed(x) if self.ape: x = x + self.absolute_pos_embed x = self.pos_drop(x) for layer in self.layers: x = layer(x) x = self.norm(x) # B L C x = self.avgpool(x.transpose(1, 2)) # B C 1 x = torch.flatten(x, 1) return x def forward(self, x): x = self.forward_features(x) x = self.head(x) return x def flops(self): flops = 0 flops += self.patch_embed.flops() for i, layer in enumerate(self.layers): flops += layer.flops() flops += self.num_features * self.patches_resolution[0] * self.patches_resolution[1] // (2 ** self.num_layers) flops += self.num_features * self.num_classes return flops
30,671
41.074074
161
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/models/swin_mlp.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, to_2tuple, trunc_normal_ class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows def window_reverse(windows, window_size, H, W): """ Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x class SwinMLPBlock(nn.Module): r""" Swin MLP Block. Args: dim (int): Number of input channels. input_resolution (tuple[int]): Input resulotion. num_heads (int): Number of attention heads. window_size (int): Window size. shift_size (int): Shift size for SW-MSA. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. drop (float, optional): Dropout rate. Default: 0.0 drop_path (float, optional): Stochastic depth rate. Default: 0.0 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0, mlp_ratio=4., drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.input_resolution = input_resolution self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size self.mlp_ratio = mlp_ratio if min(self.input_resolution) <= self.window_size: # if window size is larger than input resolution, we don't partition windows self.shift_size = 0 self.window_size = min(self.input_resolution) assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" self.padding = [self.window_size - self.shift_size, self.shift_size, self.window_size - self.shift_size, self.shift_size] # P_l,P_r,P_t,P_b self.norm1 = norm_layer(dim) # use group convolution to implement multi-head MLP self.spatial_mlp = nn.Conv1d(self.num_heads * self.window_size ** 2, self.num_heads * self.window_size ** 2, kernel_size=1, groups=self.num_heads) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, x): H, W = self.input_resolution B, L, C = x.shape assert L == H * W, "input feature has wrong size" shortcut = x x = self.norm1(x) x = x.view(B, H, W, C) # shift if self.shift_size > 0: P_l, P_r, P_t, P_b = self.padding shifted_x = F.pad(x, [0, 0, P_l, P_r, P_t, P_b], "constant", 0) else: shifted_x = x _, _H, _W, _ = shifted_x.shape # partition windows x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C # Window/Shifted-Window Spatial MLP x_windows_heads = x_windows.view(-1, self.window_size * self.window_size, self.num_heads, C // self.num_heads) x_windows_heads = x_windows_heads.transpose(1, 2) # nW*B, nH, window_size*window_size, C//nH x_windows_heads = x_windows_heads.reshape(-1, self.num_heads * self.window_size * self.window_size, C // self.num_heads) spatial_mlp_windows = self.spatial_mlp(x_windows_heads) # nW*B, nH*window_size*window_size, C//nH spatial_mlp_windows = spatial_mlp_windows.view(-1, self.num_heads, self.window_size * self.window_size, C // self.num_heads).transpose(1, 2) spatial_mlp_windows = spatial_mlp_windows.reshape(-1, self.window_size * self.window_size, C) # merge windows spatial_mlp_windows = spatial_mlp_windows.reshape(-1, self.window_size, self.window_size, C) shifted_x = window_reverse(spatial_mlp_windows, self.window_size, _H, _W) # B H' W' C # reverse shift if self.shift_size > 0: P_l, P_r, P_t, P_b = self.padding x = shifted_x[:, P_t:-P_b, P_l:-P_r, :].contiguous() else: x = shifted_x x = x.view(B, H * W, C) # FFN x = shortcut + self.drop_path(x) x = x + self.drop_path(self.mlp(self.norm2(x))) return x def extra_repr(self) -> str: return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \ f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}" def flops(self): flops = 0 H, W = self.input_resolution # norm1 flops += self.dim * H * W # Window/Shifted-Window Spatial MLP if self.shift_size > 0: nW = (H / self.window_size + 1) * (W / self.window_size + 1) else: nW = H * W / self.window_size / self.window_size flops += nW * self.dim * (self.window_size * self.window_size) * (self.window_size * self.window_size) # mlp flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio # norm2 flops += self.dim * H * W return flops class PatchMerging(nn.Module): r""" Patch Merging Layer. Args: input_resolution (tuple[int]): Resolution of input feature. dim (int): Number of input channels. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): super().__init__() self.input_resolution = input_resolution self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim) def forward(self, x): """ x: B, H*W, C """ H, W = self.input_resolution B, L, C = x.shape assert L == H * W, "input feature has wrong size" assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even." x = x.view(B, H, W, C) x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C x = self.norm(x) x = self.reduction(x) return x def extra_repr(self) -> str: return f"input_resolution={self.input_resolution}, dim={self.dim}" def flops(self): H, W = self.input_resolution flops = H * W * self.dim flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim return flops class BasicLayer(nn.Module): """ A basic Swin MLP layer for one stage. Args: dim (int): Number of input channels. input_resolution (tuple[int]): Input resolution. depth (int): Number of blocks. num_heads (int): Number of attention heads. window_size (int): Local window size. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. drop (float, optional): Dropout rate. Default: 0.0 drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. """ def __init__(self, dim, input_resolution, depth, num_heads, window_size, mlp_ratio=4., drop=0., drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): super().__init__() self.dim = dim self.input_resolution = input_resolution self.depth = depth self.use_checkpoint = use_checkpoint # build blocks self.blocks = nn.ModuleList([ SwinMLPBlock(dim=dim, input_resolution=input_resolution, num_heads=num_heads, window_size=window_size, shift_size=0 if (i % 2 == 0) else window_size // 2, mlp_ratio=mlp_ratio, drop=drop, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer) for i in range(depth)]) # patch merging layer if downsample is not None: self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer) else: self.downsample = None def forward(self, x): for blk in self.blocks: if self.use_checkpoint: x = checkpoint.checkpoint(blk, x) else: x = blk(x) if self.downsample is not None: x = self.downsample(x) return x def extra_repr(self) -> str: return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" def flops(self): flops = 0 for blk in self.blocks: flops += blk.flops() if self.downsample is not None: flops += self.downsample.flops() return flops class PatchEmbed(nn.Module): r""" Image to Patch Embedding Args: img_size (int): Image size. Default: 224. patch_size (int): Patch token size. Default: 4. in_chans (int): Number of input image channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. norm_layer (nn.Module, optional): Normalization layer. Default: None """ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] self.img_size = img_size self.patch_size = patch_size self.patches_resolution = patches_resolution self.num_patches = patches_resolution[0] * patches_resolution[1] self.in_chans = in_chans self.embed_dim = embed_dim self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None def forward(self, x): B, C, H, W = x.shape # FIXME look at relaxing size constraints assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." x = self.proj(x).flatten(2).transpose(1, 2) # B Ph*Pw C if self.norm is not None: x = self.norm(x) return x def flops(self): Ho, Wo = self.patches_resolution flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) if self.norm is not None: flops += Ho * Wo * self.embed_dim return flops class SwinMLP(nn.Module): r""" Swin MLP Args: img_size (int | tuple(int)): Input image size. Default 224 patch_size (int | tuple(int)): Patch size. Default: 4 in_chans (int): Number of input image channels. Default: 3 num_classes (int): Number of classes for classification head. Default: 1000 embed_dim (int): Patch embedding dimension. Default: 96 depths (tuple(int)): Depth of each Swin MLP layer. num_heads (tuple(int)): Number of attention heads in different layers. window_size (int): Window size. Default: 7 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4 drop_rate (float): Dropout rate. Default: 0 drop_path_rate (float): Stochastic depth rate. Default: 0.1 norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. ape (bool): If True, add absolute position embedding to the patch embedding. Default: False patch_norm (bool): If True, add normalization after patch embedding. Default: True use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False """ def __init__(self, img_size=224, patch_size=4, in_chans=3, num_classes=1000, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4., drop_rate=0., drop_path_rate=0.1, norm_layer=nn.LayerNorm, ape=False, patch_norm=True, use_checkpoint=False, **kwargs): super().__init__() self.num_classes = num_classes self.num_layers = len(depths) self.embed_dim = embed_dim self.ape = ape self.patch_norm = patch_norm self.num_features = int(embed_dim * 2 ** (self.num_layers - 1)) self.mlp_ratio = mlp_ratio # split image into non-overlapping patches self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None) num_patches = self.patch_embed.num_patches patches_resolution = self.patch_embed.patches_resolution self.patches_resolution = patches_resolution # absolute position embedding if self.ape: self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim)) trunc_normal_(self.absolute_pos_embed, std=.02) self.pos_drop = nn.Dropout(p=drop_rate) # stochastic depth dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule # build layers self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layer = BasicLayer(dim=int(embed_dim * 2 ** i_layer), input_resolution=(patches_resolution[0] // (2 ** i_layer), patches_resolution[1] // (2 ** i_layer)), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, mlp_ratio=self.mlp_ratio, drop=drop_rate, drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], norm_layer=norm_layer, downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, use_checkpoint=use_checkpoint) self.layers.append(layer) self.norm = norm_layer(self.num_features) self.avgpool = nn.AdaptiveAvgPool1d(1) self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, (nn.Linear, nn.Conv1d)): trunc_normal_(m.weight, std=.02) if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'absolute_pos_embed'} @torch.jit.ignore def no_weight_decay_keywords(self): return {'relative_position_bias_table'} def forward_features(self, x): x = self.patch_embed(x) if self.ape: x = x + self.absolute_pos_embed x = self.pos_drop(x) for layer in self.layers: x = layer(x) x = self.norm(x) # B L C x = self.avgpool(x.transpose(1, 2)) # B C 1 x = torch.flatten(x, 1) return x def forward(self, x): x = self.forward_features(x) x = self.head(x) return x def flops(self): flops = 0 flops += self.patch_embed.flops() for i, layer in enumerate(self.layers): flops += layer.flops() flops += self.num_features * self.patches_resolution[0] * self.patches_resolution[1] // (2 ** self.num_layers) flops += self.num_features * self.num_classes return flops
18,508
38.464819
118
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/models/swin_transformer.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import torch import torch.nn as nn import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, to_2tuple, trunc_normal_ class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows def window_reverse(windows, window_size, H, W): """ Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x class WindowAttention(nn.Module): r""" Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window. Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_heads (int): Number of attention heads. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 proj_drop (float, optional): Dropout ratio of output. Default: 0.0 """ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.): super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 # define a parameter table of relative position bias self.relative_position_bias_table = nn.Parameter( torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH # get pair-wise relative position index for each token inside the window coords_h = torch.arange(self.window_size[0]) coords_w = torch.arange(self.window_size[1]) coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 relative_coords[:, :, 1] += self.window_size[1] - 1 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww self.register_buffer("relative_position_index", relative_position_index) self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) trunc_normal_(self.relative_position_bias_table, std=.02) self.softmax = nn.Softmax(dim=-1) def forward(self, x, mask=None): """ Args: x: input features with shape of (num_windows*B, N, C) mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None """ B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) q = q * self.scale attn = (q @ k.transpose(-2, -1)) relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww attn = attn + relative_position_bias.unsqueeze(0) if mask is not None: nW = mask.shape[0] attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) attn = attn.view(-1, self.num_heads, N, N) attn = self.softmax(attn) else: attn = self.softmax(attn) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B_, N, C) x = self.proj(x) x = self.proj_drop(x) return x def extra_repr(self) -> str: return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}' def flops(self, N): # calculate flops for 1 window with token length of N flops = 0 # qkv = self.qkv(x) flops += N * self.dim * 3 * self.dim # attn = (q @ k.transpose(-2, -1)) flops += self.num_heads * N * (self.dim // self.num_heads) * N # x = (attn @ v) flops += self.num_heads * N * N * (self.dim // self.num_heads) # x = self.proj(x) flops += N * self.dim * self.dim return flops class SwinTransformerBlock(nn.Module): r""" Swin Transformer Block. Args: dim (int): Number of input channels. input_resolution (tuple[int]): Input resulotion. num_heads (int): Number of attention heads. window_size (int): Window size. shift_size (int): Shift size for SW-MSA. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. drop (float, optional): Dropout rate. Default: 0.0 attn_drop (float, optional): Attention dropout rate. Default: 0.0 drop_path (float, optional): Stochastic depth rate. Default: 0.0 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.input_resolution = input_resolution self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size self.mlp_ratio = mlp_ratio if min(self.input_resolution) <= self.window_size: # if window size is larger than input resolution, we don't partition windows self.shift_size = 0 self.window_size = min(self.input_resolution) assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" self.norm1 = norm_layer(dim) self.attn = WindowAttention( dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) if self.shift_size > 0: # calculate attention mask for SW-MSA H, W = self.input_resolution img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 h_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) w_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) cnt = 0 for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1 mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 mask_windows = mask_windows.view(-1, self.window_size * self.window_size) attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) else: attn_mask = None self.register_buffer("attn_mask", attn_mask) def forward(self, x): H, W = self.input_resolution B, L, C = x.shape assert L == H * W, "input feature has wrong size" shortcut = x x = self.norm1(x) x = x.view(B, H, W, C) # cyclic shift if self.shift_size > 0: shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) else: shifted_x = x # partition windows x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C # W-MSA/SW-MSA attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C # merge windows attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C # reverse cyclic shift if self.shift_size > 0: x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) else: x = shifted_x x = x.view(B, H * W, C) # FFN x = shortcut + self.drop_path(x) x = x + self.drop_path(self.mlp(self.norm2(x))) return x def extra_repr(self) -> str: return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \ f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}" def flops(self): flops = 0 H, W = self.input_resolution # norm1 flops += self.dim * H * W # W-MSA/SW-MSA nW = H * W / self.window_size / self.window_size flops += nW * self.attn.flops(self.window_size * self.window_size) # mlp flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio # norm2 flops += self.dim * H * W return flops class PatchMerging(nn.Module): r""" Patch Merging Layer. Args: input_resolution (tuple[int]): Resolution of input feature. dim (int): Number of input channels. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): super().__init__() self.input_resolution = input_resolution self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim) def forward(self, x): """ x: B, H*W, C """ H, W = self.input_resolution B, L, C = x.shape assert L == H * W, "input feature has wrong size" assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even." x = x.view(B, H, W, C) x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C x = self.norm(x) x = self.reduction(x) return x def extra_repr(self) -> str: return f"input_resolution={self.input_resolution}, dim={self.dim}" def flops(self): H, W = self.input_resolution flops = H * W * self.dim flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim return flops class BasicLayer(nn.Module): """ A basic Swin Transformer layer for one stage. Args: dim (int): Number of input channels. input_resolution (tuple[int]): Input resolution. depth (int): Number of blocks. num_heads (int): Number of attention heads. window_size (int): Local window size. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. drop (float, optional): Dropout rate. Default: 0.0 attn_drop (float, optional): Attention dropout rate. Default: 0.0 drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. """ def __init__(self, dim, input_resolution, depth, num_heads, window_size, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): super().__init__() self.dim = dim self.input_resolution = input_resolution self.depth = depth self.use_checkpoint = use_checkpoint # build blocks self.blocks = nn.ModuleList([ SwinTransformerBlock(dim=dim, input_resolution=input_resolution, num_heads=num_heads, window_size=window_size, shift_size=0 if (i % 2 == 0) else window_size // 2, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer) for i in range(depth)]) # patch merging layer if downsample is not None: self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer) else: self.downsample = None def forward(self, x): for blk in self.blocks: if self.use_checkpoint: x = checkpoint.checkpoint(blk, x) else: x = blk(x) if self.downsample is not None: x = self.downsample(x) return x def extra_repr(self) -> str: return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" def flops(self): flops = 0 for blk in self.blocks: flops += blk.flops() if self.downsample is not None: flops += self.downsample.flops() return flops class PatchEmbed(nn.Module): r""" Image to Patch Embedding Args: img_size (int): Image size. Default: 224. patch_size (int): Patch token size. Default: 4. in_chans (int): Number of input image channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. norm_layer (nn.Module, optional): Normalization layer. Default: None """ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] self.img_size = img_size self.patch_size = patch_size self.patches_resolution = patches_resolution self.num_patches = patches_resolution[0] * patches_resolution[1] self.in_chans = in_chans self.embed_dim = embed_dim self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None def forward(self, x): B, C, H, W = x.shape # FIXME look at relaxing size constraints assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." x = self.proj(x).flatten(2).transpose(1, 2) # B Ph*Pw C if self.norm is not None: x = self.norm(x) return x def flops(self): Ho, Wo = self.patches_resolution flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) if self.norm is not None: flops += Ho * Wo * self.embed_dim return flops class SwinTransformer(nn.Module): r""" Swin Transformer A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - https://arxiv.org/pdf/2103.14030 Args: img_size (int | tuple(int)): Input image size. Default 224 patch_size (int | tuple(int)): Patch size. Default: 4 in_chans (int): Number of input image channels. Default: 3 num_classes (int): Number of classes for classification head. Default: 1000 embed_dim (int): Patch embedding dimension. Default: 96 depths (tuple(int)): Depth of each Swin Transformer layer. num_heads (tuple(int)): Number of attention heads in different layers. window_size (int): Window size. Default: 7 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4 qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None drop_rate (float): Dropout rate. Default: 0 attn_drop_rate (float): Attention dropout rate. Default: 0 drop_path_rate (float): Stochastic depth rate. Default: 0.1 norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. ape (bool): If True, add absolute position embedding to the patch embedding. Default: False patch_norm (bool): If True, add normalization after patch embedding. Default: True use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False """ def __init__(self, img_size=224, patch_size=4, in_chans=3, num_classes=1000, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, norm_layer=nn.LayerNorm, ape=False, patch_norm=True, use_checkpoint=False, **kwargs): super().__init__() self.num_classes = num_classes self.num_layers = len(depths) self.embed_dim = embed_dim self.ape = ape self.patch_norm = patch_norm self.num_features = int(embed_dim * 2 ** (self.num_layers - 1)) self.mlp_ratio = mlp_ratio # split image into non-overlapping patches self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None) num_patches = self.patch_embed.num_patches patches_resolution = self.patch_embed.patches_resolution self.patches_resolution = patches_resolution # absolute position embedding if self.ape: self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim)) trunc_normal_(self.absolute_pos_embed, std=.02) self.pos_drop = nn.Dropout(p=drop_rate) # stochastic depth dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule # build layers self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layer = BasicLayer(dim=int(embed_dim * 2 ** i_layer), input_resolution=(patches_resolution[0] // (2 ** i_layer), patches_resolution[1] // (2 ** i_layer)), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, mlp_ratio=self.mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], norm_layer=norm_layer, downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, use_checkpoint=use_checkpoint) self.layers.append(layer) self.norm = norm_layer(self.num_features) self.avgpool = nn.AdaptiveAvgPool1d(1) self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'absolute_pos_embed'} @torch.jit.ignore def no_weight_decay_keywords(self): return {'relative_position_bias_table'} def forward_features(self, x): x = self.patch_embed(x) if self.ape: x = x + self.absolute_pos_embed x = self.pos_drop(x) for layer in self.layers: x = layer(x) x = self.norm(x) # B L C x = self.avgpool(x.transpose(1, 2)) # B C 1 x = torch.flatten(x, 1) return x def forward(self, x): x = self.forward_features(x) x = self.head(x) return x def flops(self): flops = 0 flops += self.patch_embed.flops() for i, layer in enumerate(self.layers): flops += layer.flops() flops += self.num_features * self.patches_resolution[0] * self.patches_resolution[1] // (2 ** self.num_layers) flops += self.num_features * self.num_classes return flops
24,234
40.356655
119
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/models/__init__.py
from .build import build_model
30
30
30
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/models/build.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- from .boat_swin_transformer import SwinTransformer from .swin_mlp import SwinMLP def build_model(config): model_type = config.MODEL.TYPE if model_type == 'swin': model = SwinTransformer(img_size=config.DATA.IMG_SIZE, patch_size=config.MODEL.SWIN.PATCH_SIZE, in_chans=config.MODEL.SWIN.IN_CHANS, num_classes=config.MODEL.NUM_CLASSES, embed_dim=config.MODEL.SWIN.EMBED_DIM, depths=config.MODEL.SWIN.DEPTHS, num_heads=config.MODEL.SWIN.NUM_HEADS, window_size=config.MODEL.SWIN.WINDOW_SIZE, mlp_ratio=config.MODEL.SWIN.MLP_RATIO, qkv_bias=config.MODEL.SWIN.QKV_BIAS, qk_scale=config.MODEL.SWIN.QK_SCALE, drop_rate=config.MODEL.DROP_RATE, drop_path_rate=config.MODEL.DROP_PATH_RATE, ape=config.MODEL.SWIN.APE, patch_norm=config.MODEL.SWIN.PATCH_NORM, use_checkpoint=config.TRAIN.USE_CHECKPOINT) elif model_type == 'swin_mlp': model = SwinMLP(img_size=config.DATA.IMG_SIZE, patch_size=config.MODEL.SWIN_MLP.PATCH_SIZE, in_chans=config.MODEL.SWIN_MLP.IN_CHANS, num_classes=config.MODEL.NUM_CLASSES, embed_dim=config.MODEL.SWIN_MLP.EMBED_DIM, depths=config.MODEL.SWIN_MLP.DEPTHS, num_heads=config.MODEL.SWIN_MLP.NUM_HEADS, window_size=config.MODEL.SWIN_MLP.WINDOW_SIZE, mlp_ratio=config.MODEL.SWIN_MLP.MLP_RATIO, drop_rate=config.MODEL.DROP_RATE, drop_path_rate=config.MODEL.DROP_PATH_RATE, ape=config.MODEL.SWIN_MLP.APE, patch_norm=config.MODEL.SWIN_MLP.PATCH_NORM, use_checkpoint=config.TRAIN.USE_CHECKPOINT) else: raise NotImplementedError(f"Unkown model: {model_type}") return model
2,566
50.34
75
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/data/__init__.py
from .build import build_loader
31
31
31
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/data/samplers.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import torch class SubsetRandomSampler(torch.utils.data.Sampler): r"""Samples elements randomly from a given list of indices, without replacement. Arguments: indices (sequence): a sequence of indices """ def __init__(self, indices): self.epoch = 0 self.indices = indices def __iter__(self): return (self.indices[i] for i in torch.randperm(len(self.indices))) def __len__(self): return len(self.indices) def set_epoch(self, epoch): self.epoch = epoch
781
25.066667
84
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/data/zipreader.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import zipfile import io import numpy as np from PIL import Image from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True def is_zip_path(img_or_path): """judge if this is a zip path""" return '.zip@' in img_or_path class ZipReader(object): """A class to read zipped files""" zip_bank = dict() def __init__(self): super(ZipReader, self).__init__() @staticmethod def get_zipfile(path): zip_bank = ZipReader.zip_bank if path not in zip_bank: zfile = zipfile.ZipFile(path, 'r') zip_bank[path] = zfile return zip_bank[path] @staticmethod def split_zip_style_path(path): pos_at = path.index('@') assert pos_at != -1, "character '@' is not found from the given path '%s'" % path zip_path = path[0: pos_at] folder_path = path[pos_at + 1:] folder_path = str.strip(folder_path, '/') return zip_path, folder_path @staticmethod def list_folder(path): zip_path, folder_path = ZipReader.split_zip_style_path(path) zfile = ZipReader.get_zipfile(zip_path) folder_list = [] for file_foler_name in zfile.namelist(): file_foler_name = str.strip(file_foler_name, '/') if file_foler_name.startswith(folder_path) and \ len(os.path.splitext(file_foler_name)[-1]) == 0 and \ file_foler_name != folder_path: if len(folder_path) == 0: folder_list.append(file_foler_name) else: folder_list.append(file_foler_name[len(folder_path) + 1:]) return folder_list @staticmethod def list_files(path, extension=None): if extension is None: extension = ['.*'] zip_path, folder_path = ZipReader.split_zip_style_path(path) zfile = ZipReader.get_zipfile(zip_path) file_lists = [] for file_foler_name in zfile.namelist(): file_foler_name = str.strip(file_foler_name, '/') if file_foler_name.startswith(folder_path) and \ str.lower(os.path.splitext(file_foler_name)[-1]) in extension: if len(folder_path) == 0: file_lists.append(file_foler_name) else: file_lists.append(file_foler_name[len(folder_path) + 1:]) return file_lists @staticmethod def read(path): zip_path, path_img = ZipReader.split_zip_style_path(path) zfile = ZipReader.get_zipfile(zip_path) data = zfile.read(path_img) return data @staticmethod def imread(path): zip_path, path_img = ZipReader.split_zip_style_path(path) zfile = ZipReader.get_zipfile(zip_path) data = zfile.read(path_img) try: im = Image.open(io.BytesIO(data)) except: print("ERROR IMG LOADED: ", path_img) random_img = np.random.rand(224, 224, 3) * 255 im = Image.fromarray(np.uint8(random_img)) return im
3,333
31.057692
89
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/data/build.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import torch import numpy as np import torch.distributed as dist from torchvision import datasets, transforms from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.data import Mixup from timm.data import create_transform from .cached_image_folder import CachedImageFolder from .samplers import SubsetRandomSampler try: from torchvision.transforms import InterpolationMode def _pil_interp(method): if method == 'bicubic': return InterpolationMode.BICUBIC elif method == 'lanczos': return InterpolationMode.LANCZOS elif method == 'hamming': return InterpolationMode.HAMMING else: # default bilinear, do we want to allow nearest? return InterpolationMode.BILINEAR except: from timm.data.transforms import _pil_interp def build_loader(config): config.defrost() dataset_train, config.MODEL.NUM_CLASSES = build_dataset(is_train=True, config=config) config.freeze() print(f"local rank {config.LOCAL_RANK} / global rank {dist.get_rank()} successfully build train dataset") dataset_val, _ = build_dataset(is_train=False, config=config) print(f"local rank {config.LOCAL_RANK} / global rank {dist.get_rank()} successfully build val dataset") num_tasks = dist.get_world_size() global_rank = dist.get_rank() if config.DATA.ZIP_MODE and config.DATA.CACHE_MODE == 'part': indices = np.arange(dist.get_rank(), len(dataset_train), dist.get_world_size()) sampler_train = SubsetRandomSampler(indices) else: sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) if config.TEST.SEQUENTIAL: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_val = torch.utils.data.distributed.DistributedSampler( dataset_val, shuffle=False ) data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=config.DATA.BATCH_SIZE, num_workers=config.DATA.NUM_WORKERS, pin_memory=config.DATA.PIN_MEMORY, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=config.DATA.BATCH_SIZE, shuffle=False, num_workers=config.DATA.NUM_WORKERS, pin_memory=config.DATA.PIN_MEMORY, drop_last=False ) # setup mixup / cutmix mixup_fn = None mixup_active = config.AUG.MIXUP > 0 or config.AUG.CUTMIX > 0. or config.AUG.CUTMIX_MINMAX is not None if mixup_active: mixup_fn = Mixup( mixup_alpha=config.AUG.MIXUP, cutmix_alpha=config.AUG.CUTMIX, cutmix_minmax=config.AUG.CUTMIX_MINMAX, prob=config.AUG.MIXUP_PROB, switch_prob=config.AUG.MIXUP_SWITCH_PROB, mode=config.AUG.MIXUP_MODE, label_smoothing=config.MODEL.LABEL_SMOOTHING, num_classes=config.MODEL.NUM_CLASSES) return dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn def build_dataset(is_train, config): transform = build_transform(is_train, config) if config.DATA.DATASET == 'imagenet': prefix = 'train' if is_train else 'val' if config.DATA.ZIP_MODE: ann_file = prefix + "_map.txt" prefix = prefix + ".zip@/" dataset = CachedImageFolder(config.DATA.DATA_PATH, ann_file, prefix, transform, cache_mode=config.DATA.CACHE_MODE if is_train else 'part') else: root = os.path.join(config.DATA.DATA_PATH, prefix) dataset = datasets.ImageFolder(root, transform=transform) nb_classes = 1000 elif config.DATA.DATASET == 'imagenet22K': raise NotImplementedError("Imagenet-22K will come soon.") else: raise NotImplementedError("We only support ImageNet Now.") return dataset, nb_classes def build_transform(is_train, config): resize_im = config.DATA.IMG_SIZE > 32 if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=config.DATA.IMG_SIZE, is_training=True, color_jitter=config.AUG.COLOR_JITTER if config.AUG.COLOR_JITTER > 0 else None, auto_augment=config.AUG.AUTO_AUGMENT if config.AUG.AUTO_AUGMENT != 'none' else None, re_prob=config.AUG.REPROB, re_mode=config.AUG.REMODE, re_count=config.AUG.RECOUNT, interpolation=config.DATA.INTERPOLATION, ) if not resize_im: # replace RandomResizedCropAndInterpolation with # RandomCrop transform.transforms[0] = transforms.RandomCrop(config.DATA.IMG_SIZE, padding=4) return transform t = [] if resize_im: if config.TEST.CROP: size = int((256 / 224) * config.DATA.IMG_SIZE) t.append( transforms.Resize(size, interpolation=_pil_interp(config.DATA.INTERPOLATION)), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(config.DATA.IMG_SIZE)) else: t.append( transforms.Resize((config.DATA.IMG_SIZE, config.DATA.IMG_SIZE), interpolation=_pil_interp(config.DATA.INTERPOLATION)) ) t.append(transforms.ToTensor()) t.append(transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD)) return transforms.Compose(t)
5,877
37.927152
113
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/data/cached_image_folder.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import io import os import time import torch.distributed as dist import torch.utils.data as data from PIL import Image from .zipreader import is_zip_path, ZipReader def has_file_allowed_extension(filename, extensions): """Checks if a file is an allowed extension. Args: filename (string): path to a file Returns: bool: True if the filename ends with a known image extension """ filename_lower = filename.lower() return any(filename_lower.endswith(ext) for ext in extensions) def find_classes(dir): classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))] classes.sort() class_to_idx = {classes[i]: i for i in range(len(classes))} return classes, class_to_idx def make_dataset(dir, class_to_idx, extensions): images = [] dir = os.path.expanduser(dir) for target in sorted(os.listdir(dir)): d = os.path.join(dir, target) if not os.path.isdir(d): continue for root, _, fnames in sorted(os.walk(d)): for fname in sorted(fnames): if has_file_allowed_extension(fname, extensions): path = os.path.join(root, fname) item = (path, class_to_idx[target]) images.append(item) return images def make_dataset_with_ann(ann_file, img_prefix, extensions): images = [] with open(ann_file, "r") as f: contents = f.readlines() for line_str in contents: path_contents = [c for c in line_str.split('\t')] im_file_name = path_contents[0] class_index = int(path_contents[1]) assert str.lower(os.path.splitext(im_file_name)[-1]) in extensions item = (os.path.join(img_prefix, im_file_name), class_index) images.append(item) return images class DatasetFolder(data.Dataset): """A generic data loader where the samples are arranged in this way: :: root/class_x/xxx.ext root/class_x/xxy.ext root/class_x/xxz.ext root/class_y/123.ext root/class_y/nsdf3.ext root/class_y/asd932_.ext Args: root (string): Root directory path. loader (callable): A function to load a sample given its path. extensions (list[string]): A list of allowed extensions. transform (callable, optional): A function/transform that takes in a sample and returns a transformed version. E.g, ``transforms.RandomCrop`` for images. target_transform (callable, optional): A function/transform that takes in the target and transforms it. Attributes: samples (list): List of (sample path, class_index) tuples """ def __init__(self, root, loader, extensions, ann_file='', img_prefix='', transform=None, target_transform=None, cache_mode="no"): # image folder mode if ann_file == '': _, class_to_idx = find_classes(root) samples = make_dataset(root, class_to_idx, extensions) # zip mode else: samples = make_dataset_with_ann(os.path.join(root, ann_file), os.path.join(root, img_prefix), extensions) if len(samples) == 0: raise (RuntimeError("Found 0 files in subfolders of: " + root + "\n" + "Supported extensions are: " + ",".join(extensions))) self.root = root self.loader = loader self.extensions = extensions self.samples = samples self.labels = [y_1k for _, y_1k in samples] self.classes = list(set(self.labels)) self.transform = transform self.target_transform = target_transform self.cache_mode = cache_mode if self.cache_mode != "no": self.init_cache() def init_cache(self): assert self.cache_mode in ["part", "full"] n_sample = len(self.samples) global_rank = dist.get_rank() world_size = dist.get_world_size() samples_bytes = [None for _ in range(n_sample)] start_time = time.time() for index in range(n_sample): if index % (n_sample // 10) == 0: t = time.time() - start_time print(f'global_rank {dist.get_rank()} cached {index}/{n_sample} takes {t:.2f}s per block') start_time = time.time() path, target = self.samples[index] if self.cache_mode == "full": samples_bytes[index] = (ZipReader.read(path), target) elif self.cache_mode == "part" and index % world_size == global_rank: samples_bytes[index] = (ZipReader.read(path), target) else: samples_bytes[index] = (path, target) self.samples = samples_bytes def __getitem__(self, index): """ Args: index (int): Index Returns: tuple: (sample, target) where target is class_index of the target class. """ path, target = self.samples[index] sample = self.loader(path) if self.transform is not None: sample = self.transform(sample) if self.target_transform is not None: target = self.target_transform(target) return sample, target def __len__(self): return len(self.samples) def __repr__(self): fmt_str = 'Dataset ' + self.__class__.__name__ + '\n' fmt_str += ' Number of datapoints: {}\n'.format(self.__len__()) fmt_str += ' Root Location: {}\n'.format(self.root) tmp = ' Transforms (if any): ' fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp))) tmp = ' Target Transforms (if any): ' fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\n', '\n' + ' ' * len(tmp))) return fmt_str IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif'] def pil_loader(path): # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) if isinstance(path, bytes): img = Image.open(io.BytesIO(path)) elif is_zip_path(path): data = ZipReader.read(path) img = Image.open(io.BytesIO(data)) else: with open(path, 'rb') as f: img = Image.open(f) return img.convert('RGB') return img.convert('RGB') def accimage_loader(path): import accimage try: return accimage.Image(path) except IOError: # Potentially a decoding problem, fall back to PIL.Image return pil_loader(path) def default_img_loader(path): from torchvision import get_image_backend if get_image_backend() == 'accimage': return accimage_loader(path) else: return pil_loader(path) class CachedImageFolder(DatasetFolder): """A generic data loader where the images are arranged in this way: :: root/dog/xxx.png root/dog/xxy.png root/dog/xxz.png root/cat/123.png root/cat/nsdf3.png root/cat/asd932_.png Args: root (string): Root directory path. transform (callable, optional): A function/transform that takes in an PIL image and returns a transformed version. E.g, ``transforms.RandomCrop`` target_transform (callable, optional): A function/transform that takes in the target and transforms it. loader (callable, optional): A function to load an image given its path. Attributes: imgs (list): List of (image path, class_index) tuples """ def __init__(self, root, ann_file='', img_prefix='', transform=None, target_transform=None, loader=default_img_loader, cache_mode="no"): super(CachedImageFolder, self).__init__(root, loader, IMG_EXTENSIONS, ann_file=ann_file, img_prefix=img_prefix, transform=transform, target_transform=target_transform, cache_mode=cache_mode) self.imgs = self.samples def __getitem__(self, index): """ Args: index (int): Index Returns: tuple: (image, target) where target is class_index of the target class. """ path, target = self.samples[index] image = self.loader(path) if self.transform is not None: img = self.transform(image) else: img = image if self.target_transform is not None: target = self.target_transform(target) return img, target
9,026
34.679842
115
py
ehrdiff
ehrdiff-main/main.py
import logging import argparse from train_util import set_seed, train_diff def main(): parser = argparse.ArgumentParser() parser.add_argument("--seed", type=int, default=2023, help="random seed for initialization") parser.add_argument( "--data_file", default='proc_data/mimic/mimic1782_train.npy', type=str, help="Path to the file of preprocessed EHRs data", ) parser.add_argument("--check_steps", default=5000, type=int, help="the interval for printing the training loss, *batch") parser.add_argument("--num_epochs", default=5000, type=int, help="number of epochs for model training") parser.add_argument("--batch_size", default=1024, type=int, help="batch size") parser.add_argument("--if_shuffle", default=True, type=bool, help="parameter for the dataloader") parser.add_argument("--if_drop_last", default=True, type=bool, help="parameter for the dataloader") parser.add_argument("--device", default="cuda:0", type=str, help="device assigned for modeling") parser.add_argument("--ehr_dim", default=1782, type=int, help="data dimension of EHR data") parser.add_argument("--time_dim", default=384, type=int, help="dimension of time embedding") parser.add_argument("--mlp_dims", nargs='+', default=[1024, 384, 384, 384, 1024], type=int, help="hidden dims for the mlp backbone") parser.add_argument("--sigma_data", default=0.14, type=float, help="init parameters for sigma_data") parser.add_argument("--p_mean", default=-1.2, type=float, help="init parameters for p_mean") parser.add_argument("--p_std", default=1.2, type=float, help="init parameters for p_std") parser.add_argument("--num_sample_steps", default=32, type=int, help="init parameters for number of discretized time steps") parser.add_argument("--sigma_min", default=0.02, type=float, help="init parameters for sigma_min") parser.add_argument("--sigma_max", default=80, type=float, help="init parameters for sigma_max") parser.add_argument("--rho", default=7, type=float, help="init parameters for rho") parser.add_argument("--lr", default=3e-4, type=float, help="learning_rate") parser.add_argument("--warmup_steps", default=20000, type=int, help="warmup portion for the 'get_linear_schedule_with_warmup'") parser.add_argument("--weight_decay", default=0., type=float, help="weigth decay value for the optimizer") parser.add_argument("--eval_samples", default=41000, type=int, help="number of samples wanted for evaluation") args = parser.parse_args() model_setting = 'sigma_data' + str(args.sigma_data) + '|' + \ 'p_mean' + str(args.p_mean) + '|' + \ 'p_std' + str(args.p_std) + '|' + \ 'steps' + str(args.num_sample_steps) + '|' + \ 'sigma_min' + str(args.sigma_min) + '|' + \ 'sigma_max' + str(args.sigma_max) + '|' + \ 'rho' + str(args.rho) args.model_setting = model_setting logging.basicConfig( # filename='logs/' + model_setting + '.log', filename='logs/' + 'trial.log', level=logging.INFO, filemode='w', format='%(name)s - %(levelname)s - %(message)s' ) set_seed(args.seed) train_diff(args) if __name__=='__main__': main()
3,833
40.673913
95
py
ehrdiff
ehrdiff-main/diffusion_util.py
# ----------------------------------- # Code adapted from: # https://github.com/lucidrains/denoising-diffusion-pytorch # ----------------------------------- import math import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, reduce def exists(val): return val is not None def default(val, d): if exists(val): return val return d() if callable(d) else d def log(t, eps = 1e-20): return torch.log(t.clamp(min = eps)) class Block(nn.Module): def __init__(self, dim_in, dim_out, *, time_emb_dim=None): super().__init__() if time_emb_dim is not None: self.time_mlp = nn.Sequential( nn.Linear(time_emb_dim, dim_in), ) self.out_proj = nn.Sequential( nn.ReLU(), nn.Linear(dim_in, dim_out), ) def forward(self, x, time_emb=None): if time_emb is not None: t_emb = self.time_mlp(time_emb) h = x + t_emb else: h = x out = self.out_proj(h) return out class LinearModel(nn.Module): def __init__( self, *, z_dim, time_dim, unit_dims, ): super().__init__() num_linears = len(unit_dims) self.time_embedding = nn.Sequential( SinusoidalPositionEmbeddings(z_dim), nn.Linear(z_dim, time_dim), nn.SiLU(), nn.Linear(time_dim, time_dim), ) self.block_in = Block(dim_in=z_dim, dim_out=unit_dims[0], time_emb_dim=time_dim) self.block_mid = nn.ModuleList() for i in range(num_linears-1): self.block_mid.append(Block(dim_in=unit_dims[i], dim_out=unit_dims[i+1])) self.block_out = Block(dim_in=unit_dims[-1], dim_out=z_dim) def forward(self, x, time_steps): t_emb = self.time_embedding(time_steps) x = self.block_in(x, t_emb) num_mid_blocks = len(self.block_mid) if num_mid_blocks > 0: for block in self.block_mid: x = block(x) x = self.block_out(x) return x class SinusoidalPositionEmbeddings(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim def forward(self, time): device = time.device half_dim = self.dim // 2 embeddings = math.log(10000) / (half_dim - 1) embeddings = torch.exp(torch.arange(half_dim, device=device) * -embeddings) embeddings = time[:, None] * embeddings[None, :] embeddings = torch.cat((embeddings.sin(), embeddings.cos()), dim=-1) return embeddings class Diffusion(nn.Module): def __init__( self, net, *, dim, num_sample_steps, sigma_min, sigma_max, sigma_data, rho, P_mean, P_std, ): super().__init__() self.net = net self.dim = dim self.sigma_min = sigma_min self.sigma_max = sigma_max self.sigma_data = sigma_data self.rho = rho self.P_mean = P_mean self.P_std = P_std self.num_sample_steps = num_sample_steps @property def device(self): return next(self.net.parameters()).device def c_skip(self, sigma): return (self.sigma_data ** 2) / (sigma ** 2 + self.sigma_data ** 2) def c_out(self, sigma): return sigma * self.sigma_data * (self.sigma_data ** 2 + sigma ** 2) ** -0.5 def c_in(self, sigma): return 1 * (sigma ** 2 + self.sigma_data ** 2) ** -0.5 def c_noise(self, sigma): return log(sigma) * 0.25 def preconditioned_network_forward(self, noised_ehr, sigma, clamp = False): batch, device = noised_ehr.shape[0], noised_ehr.device if isinstance(sigma, float): sigma = torch.full((batch,), sigma, device = device) padded_sigma = rearrange(sigma, 'b -> b 1') net_out = self.net( self.c_in(padded_sigma) * noised_ehr, self.c_noise(sigma), ) out = self.c_skip(padded_sigma) * noised_ehr + self.c_out(padded_sigma) * net_out if clamp: out = out.clamp(0, 1) return out def sample_schedule(self, num_sample_steps = None): num_sample_steps = default(num_sample_steps, self.num_sample_steps) N = num_sample_steps inv_rho = 1 / self.rho steps = torch.arange(num_sample_steps, device = self.device, dtype = torch.float32) sigmas = (self.sigma_max ** inv_rho + steps / (N - 1) * (self.sigma_min ** inv_rho - self.sigma_max ** inv_rho)) ** self.rho sigmas = F.pad(sigmas, (0, 1), value = 0.) return sigmas @torch.no_grad() def sample(self, batch_size = 32, num_sample_steps = None, clamp = True): num_sample_steps = default(num_sample_steps, self.num_sample_steps) shape = (batch_size, self.dim) sigmas = self.sample_schedule(num_sample_steps) sigmas_and_sigmas_next = list(zip(sigmas[:-1], sigmas[1:])) init_sigma = sigmas[0] ehr = init_sigma * torch.randn(shape, device = self.device) for sigma, sigma_next in sigmas_and_sigmas_next: sigma, sigma_next = map(lambda t: t.item(), (sigma, sigma_next)) model_output = self.preconditioned_network_forward(ehr, sigma, clamp = clamp) denoised_over_sigma = (ehr - model_output) / sigma ehr_next = ehr + (sigma_next - sigma) * denoised_over_sigma if sigma_next != 0: model_output_next = self.preconditioned_network_forward(ehr_next, sigma_next, clamp = clamp) denoised_prime_over_sigma = (ehr_next - model_output_next) / sigma_next ehr_next = ehr + 0.5 * (sigma_next - sigma) * (denoised_over_sigma + denoised_prime_over_sigma) ehr = ehr_next return ehr def loss_weight(self, sigma): return (sigma ** 2 + self.sigma_data ** 2) * (sigma * self.sigma_data) ** -2 def noise_distribution(self, batch_size): return (self.P_mean + self.P_std * torch.randn((batch_size,), device = self.device)).exp() def forward(self, ehr): batch_size = ehr.shape[0] sigmas = self.noise_distribution(batch_size) padded_sigmas = rearrange(sigmas, 'b -> b 1') noise = torch.randn_like(ehr) noised_ehr = ehr + padded_sigmas * noise denoised = self.preconditioned_network_forward(noised_ehr, sigmas) losses = F.mse_loss(denoised, ehr, reduction='none') losses = reduce(losses, 'b ... -> b', 'mean') losses = losses * self.loss_weight(sigmas) return losses.mean()
6,942
27.809129
132
py
ehrdiff
ehrdiff-main/train_util.py
import os import time import random import logging import numpy as np from scipy.stats import pearsonr import matplotlib.pyplot as plt import torch from torch.utils.data import DataLoader from transformers import get_cosine_schedule_with_warmup from diffusion_util import LinearModel, Diffusion def set_seed(seed=3407): os.environ['PYTHONHASHSEED'] = str(seed) random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True def train_diff(args): logging.info("Loading Data...") raw_data = np.load(args.data_file) class EHRDataset(torch.utils.data.Dataset): def __init__(self, data=raw_data): super().__init__() self.data = data def __len__(self): return self.data.shape[0] def __getitem__(self, index: int): return self.data[index] dataset = EHRDataset(raw_data) dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=args.if_shuffle, drop_last=args.if_drop_last) device = args.device model = LinearModel(z_dim=args.ehr_dim, time_dim=args.time_dim, unit_dims=args.mlp_dims) model.to(args.device) optimizer = torch.optim.AdamW([{'params': model.parameters(), 'lr': args.lr, 'weight_decay': args.weight_decay} ]) if args.if_drop_last: scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps,\ num_training_steps=(raw_data.shape[0]//args.batch_size)*args.num_epochs) else: scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps,\ num_training_steps=(raw_data.shape[0]//args.batch_size+1)*args.num_epochs) diffusion = Diffusion( model, num_sample_steps = args.num_sample_steps, dim = args.ehr_dim, sigma_min = args.sigma_min, sigma_max = args.sigma_max, sigma_data = args.sigma_data, rho = args.rho, P_mean = args.p_mean, P_std = args.p_std, ) # timestamp = time.strftime("%m_%d_%H_%M", time.localtime()) logging.info("Training...") train_dm_loss = 0 train_cnt = 0 train_steps = 0 best_corr = 0 for epoch in range(args.num_epochs): for step, batch in enumerate(dataloader): optimizer.zero_grad() batch_size = batch.shape[0] batch = batch.to(device) loss_dm = diffusion(batch) train_dm_loss += loss_dm.item() train_cnt += batch_size train_steps += 1 if train_steps % args.check_steps == 0: logging.info('[%d, %5d] dm_loss: %.10f' % (epoch+1, train_steps, train_dm_loss / train_cnt)) model.eval() if args.eval_samples < args.batch_size: syn_data = diffusion.sample(batch_size=args.eval_samples).detach().cpu().numpy() else: num_iters = args.eval_samples // args.batch_size num_left = args.eval_samples % args.batch_size syn_data = [] for _ in range(num_iters): syn_data.append(diffusion.sample(batch_size=args.batch_size).detach().cpu().numpy()) syn_data.append(diffusion.sample(batch_size=num_left).detach().cpu().numpy()) syn_data = np.concatenate(syn_data) syn_data = np.rint(np.clip(syn_data, 0, 1)) corr, nzc, flag = plot_dim_dist(raw_data, syn_data, args.model_setting, best_corr) logging.info('corr: %.4f, none-zero columns: %d'%(corr, nzc)) if flag: best_corr = corr # checkpoints_dirname = timestamp + '_' + args.model_setting # os.makedirs(checkpoints_dirname, exist_ok=True) # torch.save(model.state_dict(), checkpoints_dirname + "/model") # torch.save(optimizer.state_dict(), checkpoints_dirname + "/optim") torch.save(model.state_dict(), 'weight/model.pt') torch.save(optimizer.state_dict(), 'weight/optim.pt') logging.info("New Weight saved!") logging.info("**************************************") model.train() loss_dm.backward() optimizer.step() scheduler.step() def plot_dim_dist(train_data, syn_data, model_setting, best_corr): train_data_mean = np.mean(train_data, axis = 0) temp_data_mean = np.mean(syn_data, axis = 0) corr = pearsonr(temp_data_mean, train_data_mean) nzc = sum(temp_data_mean[i] > 0 for i in range(temp_data_mean.shape[0])) fig, ax = plt.subplots(figsize=(8, 6)) slope, intercept = np.polyfit(train_data_mean, temp_data_mean, 1) fitted_values = [slope * i + intercept for i in train_data_mean] identity_values = [1 * i + 0 for i in train_data_mean] ax.plot(train_data_mean, fitted_values, 'b', alpha=0.5) ax.plot(train_data_mean, identity_values, 'r', alpha=0.5) ax.scatter(train_data_mean, temp_data_mean, alpha=0.3) ax.set_title('corr: %.4f, none-zero columns: %d, slope: %.4f'%(corr[0], nzc, slope)) ax.set_xlabel('Feature prevalence of real data') ax.set_ylabel('Feature prevalence of synthetic data') # fig.savefig('figs/{}.png'.format('Current_' + model_setting)) fig.savefig('figs/{}.png'.format('Cur_res')) flag = False if corr[0] > best_corr: best_corr = corr[0] flag = True # fig.savefig('figs/{}.png'.format('Best_' + model_setting)) fig.savefig('figs/{}.png'.format('Best_res')) plt.close(fig) return corr[0], nzc, flag
6,141
36.680982
119
py
ehrdiff
ehrdiff-main/gen_dat.py
from tqdm import tqdm import torch import numpy as np from diffusion_util import LinearModel, Diffusion device = torch.device('cuda:0') dm = LinearModel(z_dim=1782, time_dim=384, unit_dims=[1024, 384, 384, 384, 1024]) dm.load_state_dict(torch.load("weight/model.pt")) dm.to(device) diffusion = Diffusion( dm, dim = 1782, P_mean = -1.2, P_std = 1.2, sigma_data = 0.14, num_sample_steps = 32, sigma_min = 0.02, sigma_max = 80, rho = 7, ) out = [] dm.eval() for b in tqdm(range(41), desc='Sampling...'): sampled_seq = diffusion.sample(batch_size=1000) out.append(sampled_seq) out_seq = torch.cat(out) out_seq = out_seq.detach().cpu().numpy() res = np.rint(np.clip(out_seq, 0, 1)) np.save("EHRDiff", out_seq)
1,016
26.486486
81
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_TextCNN/utils.py
# utils.py import torch from torchtext import data from torchtext.vocab import Vectors import spacy import pandas as pd import numpy as np from sklearn.metrics import accuracy_score class Dataset(object): def __init__(self, config): self.config = config self.train_iterator = None self.test_iterator = None self.val_iterator = None self.vocab = [] self.word_embeddings = {} def parse_label(self, label): ''' Get the actual labels from label string Input: label (string) : labels of the form '__label__2' Returns: label (int) : integer value corresponding to label string ''' return int(label.strip()[-1]) def get_pandas_df(self, filename): ''' Load the data into Pandas.DataFrame object This will be used to convert data to torchtext object ''' with open(filename, 'r') as datafile: data = [line.strip().split(',', maxsplit=1) for line in datafile] data_text = list(map(lambda x: x[1], data)) data_label = list(map(lambda x: self.parse_label(x[0]), data)) full_df = pd.DataFrame({"text":data_text, "label":data_label}) return full_df def load_data(self, w2v_file, train_file, test_file, val_file=None): ''' Loads the data from files Sets up iterators for training, validation and test data Also create vocabulary and word embeddings based on the data Inputs: w2v_file (String): absolute path to file containing word embeddings (GloVe/Word2Vec) train_file (String): absolute path to training file test_file (String): absolute path to test file val_file (String): absolute path to validation file ''' NLP = spacy.load('en') tokenizer = lambda sent: [x.text for x in NLP.tokenizer(sent) if x.text != " "] # Creating Field for data TEXT = data.Field(sequential=True, tokenize=tokenizer, lower=True, fix_length=self.config.max_sen_len) LABEL = data.Field(sequential=False, use_vocab=False) datafields = [("text",TEXT),("label",LABEL)] # Load data from pd.DataFrame into torchtext.data.Dataset train_df = self.get_pandas_df(train_file) train_examples = [data.Example.fromlist(i, datafields) for i in train_df.values.tolist()] train_data = data.Dataset(train_examples, datafields) test_df = self.get_pandas_df(test_file) test_examples = [data.Example.fromlist(i, datafields) for i in test_df.values.tolist()] test_data = data.Dataset(test_examples, datafields) # If validation file exists, load it. Otherwise get validation data from training data if val_file: val_df = self.get_pandas_df(val_file) val_examples = [data.Example.fromlist(i, datafields) for i in val_df.values.tolist()] val_data = data.Dataset(val_examples, datafields) else: train_data, val_data = train_data.split(split_ratio=0.8) TEXT.build_vocab(train_data, vectors=Vectors(w2v_file)) self.word_embeddings = TEXT.vocab.vectors self.vocab = TEXT.vocab self.train_iterator = data.BucketIterator( (train_data), batch_size=self.config.batch_size, sort_key=lambda x: len(x.text), repeat=False, shuffle=True) self.val_iterator, self.test_iterator = data.BucketIterator.splits( (val_data, test_data), batch_size=self.config.batch_size, sort_key=lambda x: len(x.text), repeat=False, shuffle=False) print ("Loaded {} training examples".format(len(train_data))) print ("Loaded {} test examples".format(len(test_data))) print ("Loaded {} validation examples".format(len(val_data))) def evaluate_model(model, iterator): all_preds = [] all_y = [] for idx,batch in enumerate(iterator): if torch.cuda.is_available(): x = batch.text.cuda() else: x = batch.text y_pred = model(x) predicted = torch.max(y_pred.cpu().data, 1)[1] + 1 all_preds.extend(predicted.numpy()) all_y.extend(batch.label.numpy()) score = accuracy_score(all_y, np.array(all_preds).flatten()) return score
4,498
37.452991
110
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_TextCNN/model.py
# model.py import torch from torch import nn import numpy as np from utils import * class TextCNN(nn.Module): def __init__(self, config, vocab_size, word_embeddings): super(TextCNN, self).__init__() self.config = config # Embedding Layer self.embeddings = nn.Embedding(vocab_size, self.config.embed_size) self.embeddings.weight = nn.Parameter(word_embeddings, requires_grad=False) # This stackoverflow thread clarifies how conv1d works # https://stackoverflow.com/questions/46503816/keras-conv1d-layer-parameters-filters-and-kernel-size/46504997 self.conv1 = nn.Sequential( nn.Conv1d(in_channels=self.config.embed_size, out_channels=self.config.num_channels, kernel_size=self.config.kernel_size[0]), nn.ReLU(), nn.MaxPool1d(self.config.max_sen_len - self.config.kernel_size[0]+1) ) self.conv2 = nn.Sequential( nn.Conv1d(in_channels=self.config.embed_size, out_channels=self.config.num_channels, kernel_size=self.config.kernel_size[1]), nn.ReLU(), nn.MaxPool1d(self.config.max_sen_len - self.config.kernel_size[1]+1) ) self.conv3 = nn.Sequential( nn.Conv1d(in_channels=self.config.embed_size, out_channels=self.config.num_channels, kernel_size=self.config.kernel_size[2]), nn.ReLU(), nn.MaxPool1d(self.config.max_sen_len - self.config.kernel_size[2]+1) ) self.dropout = nn.Dropout(self.config.dropout_keep) # Fully-Connected Layer self.fc = nn.Linear(self.config.num_channels*len(self.config.kernel_size), self.config.output_size) # Softmax non-linearity self.softmax = nn.Softmax() def forward(self, x): # x.shape = (max_sen_len, batch_size) embedded_sent = self.embeddings(x).permute(1,2,0) # embedded_sent.shape = (batch_size=64,embed_size=300,max_sen_len=20) conv_out1 = self.conv1(embedded_sent).squeeze(2) #shape=(64, num_channels, 1) (squeeze 1) conv_out2 = self.conv2(embedded_sent).squeeze(2) conv_out3 = self.conv3(embedded_sent).squeeze(2) all_out = torch.cat((conv_out1, conv_out2, conv_out3), 1) final_feature_map = self.dropout(all_out) final_out = self.fc(final_feature_map) return self.softmax(final_out) def add_optimizer(self, optimizer): self.optimizer = optimizer def add_loss_op(self, loss_op): self.loss_op = loss_op def reduce_lr(self): print("Reducing LR") for g in self.optimizer.param_groups: g['lr'] = g['lr'] / 2 def run_epoch(self, train_iterator, val_iterator, epoch): train_losses = [] val_accuracies = [] losses = [] # Reduce learning rate as number of epochs increase if (epoch == int(self.config.max_epochs/3)) or (epoch == int(2*self.config.max_epochs/3)): self.reduce_lr() for i, batch in enumerate(train_iterator): self.optimizer.zero_grad() if torch.cuda.is_available(): x = batch.text.cuda() y = (batch.label - 1).type(torch.cuda.LongTensor) else: x = batch.text y = (batch.label - 1).type(torch.LongTensor) y_pred = self.__call__(x) loss = self.loss_op(y_pred, y) loss.backward() losses.append(loss.data.cpu().numpy()) self.optimizer.step() if i % 100 == 0: print("Iter: {}".format(i+1)) avg_train_loss = np.mean(losses) train_losses.append(avg_train_loss) print("\tAverage training loss: {:.5f}".format(avg_train_loss)) losses = [] # Evalute Accuracy on validation set val_accuracy = evaluate_model(self, val_iterator) print("\tVal Accuracy: {:.4f}".format(val_accuracy)) self.train() return train_losses, val_accuracies
4,215
39.932039
137
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_TextCNN/config.py
# config.py class Config(object): embed_size = 300 num_channels = 100 kernel_size = [3,4,5] output_size = 4 max_epochs = 15 lr = 0.3 batch_size = 64 max_sen_len = 30 dropout_keep = 0.8
221
17.5
25
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_TextCNN/train.py
# train.py from utils import * from model import * from config import Config import sys import torch.optim as optim from torch import nn import torch if __name__=='__main__': config = Config() train_file = '../data/ag_news.train' if len(sys.argv) > 2: train_file = sys.argv[1] test_file = '../data/ag_news.test' if len(sys.argv) > 3: test_file = sys.argv[2] w2v_file = '../data/glove.840B.300d.txt' dataset = Dataset(config) dataset.load_data(w2v_file, train_file, test_file) # Create Model with specified optimizer and loss function ############################################################## model = TextCNN(config, len(dataset.vocab), dataset.word_embeddings) if torch.cuda.is_available(): model.cuda() model.train() optimizer = optim.SGD(model.parameters(), lr=config.lr) NLLLoss = nn.NLLLoss() model.add_optimizer(optimizer) model.add_loss_op(NLLLoss) ############################################################## train_losses = [] val_accuracies = [] for i in range(config.max_epochs): print ("Epoch: {}".format(i)) train_loss,val_accuracy = model.run_epoch(dataset.train_iterator, dataset.val_iterator, i) train_losses.append(train_loss) val_accuracies.append(val_accuracy) train_acc = evaluate_model(model, dataset.train_iterator) val_acc = evaluate_model(model, dataset.val_iterator) test_acc = evaluate_model(model, dataset.test_iterator) print ('Final Training Accuracy: {:.4f}'.format(train_acc)) print ('Final Validation Accuracy: {:.4f}'.format(val_acc)) print ('Final Test Accuracy: {:.4f}'.format(test_acc))
1,720
32.096154
98
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_TextCNN/old_code/utils.py
# utils.py from nltk import word_tokenize from tqdm import tqdm from gensim.models import KeyedVectors import numpy as np import math class Vocab(object): def __init__(self): self.word_to_index = {} self.index_to_word = {} self.unknown = '<unk>' self.add_word(self.unknown) def add_word(self, word): ''' Add a word to the vocabulary Inputs: word (string) : Word to be added to vocabulary ''' if word not in self.word_to_index: index = len(self.word_to_index) self.word_to_index[word] = index self.index_to_word[index] = word def construct(self, words): ''' Construct the vocabulary Inputs: words (list[string]) : List of words defining the vocabulary ''' for word in words: self.add_word(word) print ("Constructed vocabulary of size: {}".format(len(self.word_to_index))) def encode(self, word): ''' Given a word, get corresponding index in vocabulary. ''' if word not in self.word_to_index: word = self.unknown return self.word_to_index(word) def decode(self, index): ''' Given a word index, get corresponding word from vocabulary. ''' return self.index_to_word(index) def __len__(self): return len(self.word_to_index) def parse_label(label): ''' Get the actual labels from label string Input: label (string) : labels of the form '__label__2' Returns: label (int) : integer value corresponding to label string ''' return int(label.strip()[-1]) def get_data(filename): ''' Loads the data from file Inputs: filename (String): absolute path to the datafile Returns: X (list[string]): list of contents of documents y (list[integer]): labels of documents vocab : Vocab object corresponding to words in X ''' print ('Reading data from {}'.format(filename)) with open(filename, 'r') as datafile: data = [line.strip().split(',', maxsplit=1) for line in datafile] data_text = list(map(lambda x: x[1], data)) data_label = list(map(lambda x: parse_label(x[0]), data)) vocab = Vocab() words = set(' '.join(data_text).lower().split()) vocab.construct(list(words)) return data_text, data_label, vocab def get_word_embeddings(w2vfile, word_to_index, embedsize=300): ''' For each word in our vocabulary, get the word2vec encoding of the word Inputs: w2vfile (string) : Path to the file containing (pre-trained) word embeddings embedsize (int) : Length of each word vector Returns: word_embeddings : Dictionary mapping each word to corresponding embedding ''' word_embeddings = {} if w2vfile.endswith('.txt'): f = open(w2vfile) for line in tqdm(f): values = line.split(" ") word = values[0] coefs = np.asarray(values[1:], dtype='float32') if word in word_to_index: word_embeddings[word] = coefs f.close() elif w2vfile.endswith('.bin'): word2vec = KeyedVectors.load_word2vec_format(w2vfile, binary=True, limit=1000000) for word in tqdm(word_to_index): try: word_embeddings[word] = word2vec[word.lower()] except KeyError: pass else: print ('Can\'t load word embeddings.') exit(-1) print('Found {0}/{1} word vectors.'.format(len(word_embeddings), len(word_to_index))) if len(word_to_index) > len(word_embeddings): print('Initializing remaining {} word vectors with zeros.'.format(len(word_to_index) - len(word_embeddings))) for word in word_to_index: if word not in word_embeddings: word_embeddings[word] = np.zeros((embedsize,)) return word_embeddings def encode_text(text, word_embeddings, max_sen_len): ''' Encode a sequence of words into corresponding vector representation Input: text (string) : text (space separated words, etc..) word_embeddings (dict) : dictionary mapping from words to their representation max_sen_len (int) : maximum sentence length (in words) Returns: X (np.matrix) : matrix of shape (max_sen_len, embedding_size) after zero padding ''' default_embed = np.zeros(300) words = word_tokenize(text)[:max_sen_len] embeds = [word_embeddings.get(x, default_embed) for x in words] embeds += [default_embed] * (max_sen_len - len(embeds)) return np.array(embeds, dtype=np.float32) def data_iterator(train_x, train_y, batch_size = 256): ''' Generate batches of training data for training (for single epoch) Inputs: train_df (pd.DataFrame) : complete training data batch_size (int) : Size of each batch Returns: text_arr (np.matrix) : Matrix of shape (batch_size,embed_size) lebel_arr (np.array) : Labels of this batch. Array of shape (batch_size,) ''' n_batches = math.ceil(len(train_x) / batch_size) for idx in range(n_batches): x = train_x[idx *batch_size:(idx+1) * batch_size] y = train_y[idx *batch_size:(idx+1) * batch_size] yield x, y
5,381
33.722581
117
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_TextCNN/old_code/model.py
# model.py import torch from torch import nn from torch import Tensor from torch.autograd import Variable import numpy as np from sklearn.metrics import accuracy_score class CNNText(nn.Module): def __init__(self, config): super(CNNText, self).__init__() self.config = config # Convolutional Layer # We use 3 kernels as in original paper # Size of kernels: (3,300),(4,300),(5,300) self.conv1 = nn.Conv2d(in_channels=self.config.in_channels, out_channels=self.config.num_channels, kernel_size=(self.config.kernel_size[0],self.config.embed_size), stride=1, padding=0) self.activation1 = nn.ReLU() self.max_out1 = nn.MaxPool1d(self.config.max_sen_len - self.config.kernel_size[0]+1) self.conv2 = nn.Conv2d(in_channels=self.config.in_channels, out_channels=self.config.num_channels, kernel_size=(self.config.kernel_size[1],self.config.embed_size), stride=1, padding=0) self.activation2 = nn.ReLU() self.max_out2 = nn.MaxPool1d(self.config.max_sen_len - self.config.kernel_size[1]+1) self.conv3 = nn.Conv2d(in_channels=self.config.in_channels, out_channels=self.config.num_channels, kernel_size=(self.config.kernel_size[2],self.config.embed_size), stride=1, padding=0) self.activation3 = nn.ReLU() self.max_out3 = nn.MaxPool1d(self.config.max_sen_len - self.config.kernel_size[2]+1) self.dropout = nn.Dropout(self.config.dropout_keep) # Fully-Connected Layer self.fc = nn.Linear(self.config.num_channels*len(self.config.kernel_size), self.config.output_size) # Softmax non-linearity self.softmax = nn.Softmax() def forward(self, x): x = x.unsqueeze(1) # (batch_size,max_seq_len,embed_size) => (batch_size,1,max_seq_len,embed_size) conv_out1 = self.conv1(x).squeeze(3) activation_out1 = self.activation1(conv_out1) max_out1 = self.max_out1(activation_out1).squeeze(2) conv_out2 = self.conv2(x).squeeze(3) activation_out2 = self.activation2(conv_out2) max_out2 = self.max_out2(activation_out2).squeeze(2) conv_out3 = self.conv3(x).squeeze(3) activation_out3 = self.activation3(conv_out3) max_out3 = self.max_out3(activation_out3).squeeze(2) all_out = torch.cat((max_out1, max_out2, max_out3), 1) final_feature_map = self.dropout(all_out) final_out = self.fc(final_feature_map) return self.softmax(final_out) def add_optimizer(self, optimizer): self.optimizer = optimizer def add_loss_op(self, loss_op): self.loss_op = loss_op def run_epoch(self, train_data, val_data): train_x, train_y = train_data[0], train_data[1] val_x, val_y = val_data[0], val_data[1] iterator = data_iterator(train_x, train_y, self.config.batch_size) train_losses = [] val_accuracies = [] losses = [] for i, (x,y) in enumerate(iterator): self.optimizer.zero_grad() x = Tensor(x).cuda() y_pred = self.__call__(x) loss = self.loss_op(y_pred, torch.cuda.LongTensor(y-1)) loss.backward() losses.append(loss.data.cpu().numpy()) self.optimizer.step() if (i + 1) % 50 == 0: print("Iter: {}".format(i+1)) avg_train_loss = np.mean(losses) train_losses.append(avg_train_loss) print("\tAverage training loss: {:.5f}".format(avg_train_loss)) losses = [] # Evalute Accuracy on validation set self.eval() all_preds = [] val_iterator = data_iterator(val_x, val_y, self.config.batch_size) for j, (x,y) in enumerate(val_iterator): x = Variable(Tensor(x)) y_pred = self.__call__(x.cuda()) predicted = torch.max(y_pred.cpu().data, 1)[1] + 1 all_preds.extend(predicted.numpy()) score = accuracy_score(val_y, np.array(all_preds).flatten()) val_accuracies.append(score) print("\tVal Accuracy: {:.4f}".format(score)) self.train() return train_losses, val_accuracies
4,642
40.088496
107
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_TextCNN/old_code/config.py
# config.py class Config(object): embed_size = 300 in_channels = 1 num_channels = 100 kernel_size = [3,4,5] output_size = 4 max_epochs = 10 lr = 0.25 batch_size = 64 max_sen_len = 20 dropout_keep = 0.6
242
17.692308
25
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_TextCNN/old_code/train.py
# train.py from utils import * from config import Config from sklearn.model_selection import train_test_split import numpy as np from tqdm import tqdm import sys import torch.optim as optim from torch import nn, Tensor from torch.autograd import Variable import torch from sklearn.metrics import accuracy_score def get_accuracy(model, test_x, test_y): all_preds = [] test_iterator = data_iterator(test_x, test_y) for x, y in test_iterator: x = Variable(Tensor(x)) y_pred = model(x.cuda()) predicted = torch.max(y_pred.cpu().data, 1)[1] + 1 all_preds.extend(predicted.numpy()) score = accuracy_score(test_y, np.array(all_preds).flatten()) return score if __name__=='__main__': train_path = '../data/ag_news.train' if len(sys.argv) > 2: train_path = sys.argv[1] test_path = '../data/ag_news.test' if len(sys.argv) > 3: test_path = sys.argv[2] train_text, train_labels, vocab = get_data(train_path) train_text, val_text, train_label, val_label = train_test_split(train_text, train_labels, test_size=0.2) # Read Word Embeddings w2vfile = '../data/glove.840B.300d.txt' word_embeddings = get_word_embeddings(w2vfile, vocab.word_to_index, embedsize=300) # Get all configuration parameters config = Config() train_x = np.array([encode_text(text, word_embeddings, config.max_sen_len) for text in tqdm(train_text)]) #(num_examples, max_sen_len, embed_size) train_y = np.array(train_label) #(num_examples) val_x = np.array([encode_text(text, word_embeddings, config.max_sen_len) for text in tqdm(val_text)]) val_y = np.array(val_label) # Create Model with specified optimizer and loss function ############################################################## model = CNNText(config) model.cuda() model.train() optimizer = optim.SGD(model.parameters(), lr=config.lr) NLLLoss = nn.NLLLoss() model.add_optimizer(optimizer) model.add_loss_op(NLLLoss) ############################################################## train_data = [train_x, train_y] val_data = [val_x, val_y] for i in range(config.max_epochs): print ("Epoch: {}".format(i)) train_losses,val_accuracies = model.run_epoch(train_data, val_data) print("\tAverage training loss: {:.5f}".format(np.mean(train_losses))) print("\tAverage Val Accuracy (per 50 iterations): {:.4f}".format(np.mean(val_accuracies))) # Reduce learning rate as number of epochs increase if i > 0.5 * config.max_epochs: print("Reducing LR") for g in optimizer.param_groups: g['lr'] = 0.1 if i > 0.75 * config.max_epochs: print("Reducing LR") for g in optimizer.param_groups: g['lr'] = 0.05 # Get Accuracy of final model test_text, test_labels, test_vocab = get_data(test_path) test_x = np.array([encode_text(text, word_embeddings, config.max_sen_len) for text in tqdm(test_text)]) test_y = np.array(test_labels) train_acc = get_accuracy(model, train_x, train_y) val_acc = get_accuracy(model, val_x, val_y) test_acc = get_accuracy(model, test_x, test_y) print ('Final Training Accuracy: {:.4f}'.format(train_acc)) print ('Final Validation Accuracy: {:.4f}'.format(val_acc)) print ('Final Test Accuracy: {:.4f}'.format(test_acc))
3,445
36.868132
150
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_Seq2Seq_Attention/utils.py
# utils.py import torch from torchtext import data from torchtext.vocab import Vectors import spacy import pandas as pd import numpy as np from sklearn.metrics import accuracy_score class Dataset(object): def __init__(self, config): self.config = config self.train_iterator = None self.test_iterator = None self.val_iterator = None self.vocab = [] self.word_embeddings = {} def parse_label(self, label): ''' Get the actual labels from label string Input: label (string) : labels of the form '__label__2' Returns: label (int) : integer value corresponding to label string ''' return int(label.strip()[-1]) def get_pandas_df(self, filename): ''' Load the data into Pandas.DataFrame object This will be used to convert data to torchtext object ''' with open(filename, 'r') as datafile: data = [line.strip().split(',', maxsplit=1) for line in datafile] data_text = list(map(lambda x: x[1], data)) data_label = list(map(lambda x: self.parse_label(x[0]), data)) full_df = pd.DataFrame({"text":data_text, "label":data_label}) return full_df def load_data(self, w2v_file, train_file, test_file=None, val_file=None): ''' Loads the data from files Sets up iterators for training, validation and test data Also create vocabulary and word embeddings based on the data Inputs: w2v_file (String): path to file containing word embeddings (GloVe/Word2Vec) train_file (String): path to training file test_file (String): path to test file val_file (String): path to validation file ''' NLP = spacy.load('en') tokenizer = lambda sent: [x.text for x in NLP.tokenizer(sent) if x.text != " "] # Creating Field for data TEXT = data.Field(sequential=True, tokenize=tokenizer, lower=True, fix_length=self.config.max_sen_len) LABEL = data.Field(sequential=False, use_vocab=False) datafields = [("text",TEXT),("label",LABEL)] # Load data from pd.DataFrame into torchtext.data.Dataset train_df = self.get_pandas_df(train_file) train_examples = [data.Example.fromlist(i, datafields) for i in train_df.values.tolist()] train_data = data.Dataset(train_examples, datafields) test_df = self.get_pandas_df(test_file) test_examples = [data.Example.fromlist(i, datafields) for i in test_df.values.tolist()] test_data = data.Dataset(test_examples, datafields) # If validation file exists, load it. Otherwise get validation data from training data if val_file: val_df = self.get_pandas_df(val_file) val_examples = [data.Example.fromlist(i, datafields) for i in val_df.values.tolist()] val_data = data.Dataset(val_examples, datafields) else: train_data, val_data = train_data.split(split_ratio=0.8) if w2v_file: TEXT.build_vocab(train_data, vectors=Vectors(w2v_file)) self.word_embeddings = TEXT.vocab.vectors self.vocab = TEXT.vocab self.train_iterator = data.BucketIterator( (train_data), batch_size=self.config.batch_size, sort_key=lambda x: len(x.text), repeat=False, shuffle=True) self.val_iterator, self.test_iterator = data.BucketIterator.splits( (val_data, test_data), batch_size=self.config.batch_size, sort_key=lambda x: len(x.text), repeat=False, shuffle=False) print ("Loaded {} training examples".format(len(train_data))) print ("Loaded {} test examples".format(len(test_data))) print ("Loaded {} validation examples".format(len(val_data))) def evaluate_model(model, iterator): all_preds = [] all_y = [] for idx,batch in enumerate(iterator): if torch.cuda.is_available(): x = batch.text.cuda() else: x = batch.text y_pred = model(x) predicted = torch.max(y_pred.cpu().data, 1)[1] + 1 all_preds.extend(predicted.numpy()) all_y.extend(batch.label.numpy()) score = accuracy_score(all_y, np.array(all_preds).flatten()) return score
4,492
37.076271
110
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_Seq2Seq_Attention/model.py
# model.py import torch from torch import nn import numpy as np from torch.nn import functional as F from utils import * class Seq2SeqAttention(nn.Module): def __init__(self, config, vocab_size, word_embeddings): super(Seq2SeqAttention, self).__init__() self.config = config # Embedding Layer self.embeddings = nn.Embedding(vocab_size, self.config.embed_size) self.embeddings.weight = nn.Parameter(word_embeddings, requires_grad=False) # Encoder RNN self.lstm = nn.LSTM(input_size = self.config.embed_size, hidden_size = self.config.hidden_size, num_layers = self.config.hidden_layers, bidirectional = self.config.bidirectional) # Dropout Layer self.dropout = nn.Dropout(self.config.dropout_keep) # Fully-Connected Layer self.fc = nn.Linear( self.config.hidden_size * (1+self.config.bidirectional) * 2, self.config.output_size ) # Softmax non-linearity self.softmax = nn.Softmax() def apply_attention(self, rnn_output, final_hidden_state): ''' Apply Attention on RNN output Input: rnn_output (batch_size, seq_len, num_directions * hidden_size): tensor representing hidden state for every word in the sentence final_hidden_state (batch_size, num_directions * hidden_size): final hidden state of the RNN Returns: attention_output(batch_size, num_directions * hidden_size): attention output vector for the batch ''' hidden_state = final_hidden_state.unsqueeze(2) attention_scores = torch.bmm(rnn_output, hidden_state).squeeze(2) soft_attention_weights = F.softmax(attention_scores, 1).unsqueeze(2) #shape = (batch_size, seq_len, 1) attention_output = torch.bmm(rnn_output.permute(0,2,1), soft_attention_weights).squeeze(2) return attention_output def forward(self, x): # x.shape = (max_sen_len, batch_size) embedded_sent = self.embeddings(x) # embedded_sent.shape = (max_sen_len=20, batch_size=64,embed_size=300) ##################################### Encoder ####################################### lstm_output, (h_n,c_n) = self.lstm(embedded_sent) # lstm_output.shape = (seq_len, batch_size, num_directions * hidden_size) # Final hidden state of last layer (num_directions, batch_size, hidden_size) batch_size = h_n.shape[1] h_n_final_layer = h_n.view(self.config.hidden_layers, self.config.bidirectional + 1, batch_size, self.config.hidden_size)[-1,:,:,:] ##################################### Attention ##################################### # Convert input to (batch_size, num_directions * hidden_size) for attention final_hidden_state = torch.cat([h_n_final_layer[i,:,:] for i in range(h_n_final_layer.shape[0])], dim=1) attention_out = self.apply_attention(lstm_output.permute(1,0,2), final_hidden_state) # Attention_out.shape = (batch_size, num_directions * hidden_size) #################################### Linear ######################################### concatenated_vector = torch.cat([final_hidden_state, attention_out], dim=1) final_feature_map = self.dropout(concatenated_vector) # shape=(batch_size, num_directions * hidden_size) final_out = self.fc(final_feature_map) return self.softmax(final_out) def add_optimizer(self, optimizer): self.optimizer = optimizer def add_loss_op(self, loss_op): self.loss_op = loss_op def reduce_lr(self): print("Reducing LR") for g in self.optimizer.param_groups: g['lr'] = g['lr'] / 2 def run_epoch(self, train_iterator, val_iterator, epoch): train_losses = [] val_accuracies = [] losses = [] # Reduce learning rate as number of epochs increase if (epoch == int(self.config.max_epochs/3)) or (epoch == int(2*self.config.max_epochs/3)): self.reduce_lr() for i, batch in enumerate(train_iterator): self.optimizer.zero_grad() if torch.cuda.is_available(): x = batch.text.cuda() y = (batch.label - 1).type(torch.cuda.LongTensor) else: x = batch.text y = (batch.label - 1).type(torch.LongTensor) y_pred = self.__call__(x) loss = self.loss_op(y_pred, y) loss.backward() losses.append(loss.data.cpu().numpy()) self.optimizer.step() if i % 100 == 0: print("Iter: {}".format(i+1)) avg_train_loss = np.mean(losses) train_losses.append(avg_train_loss) print("\tAverage training loss: {:.5f}".format(avg_train_loss)) losses = [] # Evalute Accuracy on validation set val_accuracy = evaluate_model(self, val_iterator) print("\tVal Accuracy: {:.4f}".format(val_accuracy)) self.train() return train_losses, val_accuracies
5,529
42.203125
139
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_Seq2Seq_Attention/config.py
# config.py class Config(object): embed_size = 300 hidden_layers = 1 hidden_size = 32 bidirectional = True output_size = 4 max_epochs = 15 lr = 0.5 batch_size = 128 dropout_keep = 0.8 max_sen_len = None # Sequence length for RNN
269
19.769231
48
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_Seq2Seq_Attention/train.py
# train.py from utils import * from model import * from config import Config import sys import torch.optim as optim from torch import nn import torch if __name__=='__main__': config = Config() train_file = '../data/ag_news.train' if len(sys.argv) > 2: train_file = sys.argv[1] test_file = '../data/ag_news.test' if len(sys.argv) > 3: test_file = sys.argv[2] w2v_file = '../data/glove.840B.300d.txt' dataset = Dataset(config) dataset.load_data(w2v_file, train_file, test_file) # Create Model with specified optimizer and loss function ############################################################## model = Seq2SeqAttention(config, len(dataset.vocab), dataset.word_embeddings) if torch.cuda.is_available(): model.cuda() model.train() optimizer = optim.SGD(model.parameters(), lr=config.lr) NLLLoss = nn.NLLLoss() model.add_optimizer(optimizer) model.add_loss_op(NLLLoss) ############################################################## train_losses = [] val_accuracies = [] for i in range(config.max_epochs): print ("Epoch: {}".format(i)) train_loss,val_accuracy = model.run_epoch(dataset.train_iterator, dataset.val_iterator, i) train_losses.append(train_loss) val_accuracies.append(val_accuracy) train_acc = evaluate_model(model, dataset.train_iterator) val_acc = evaluate_model(model, dataset.val_iterator) test_acc = evaluate_model(model, dataset.test_iterator) print ('Final Training Accuracy: {:.4f}'.format(train_acc)) print ('Final Validation Accuracy: {:.4f}'.format(val_acc)) print ('Final Test Accuracy: {:.4f}'.format(test_acc))
1,729
32.269231
98
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_CharCNN/utils.py
# utils.py import torch from torchtext import data import pandas as pd import numpy as np from sklearn.metrics import accuracy_score def get_embedding_matrix(vocab_chars): # one hot embedding plus all-zero vector vocabulary_size = len(vocab_chars) onehot_matrix = np.eye(vocabulary_size, vocabulary_size) return onehot_matrix class Dataset(object): def __init__(self, config): self.config = config self.train_iterator = None self.test_iterator = None self.val_iterator = None def parse_label(self, label): ''' Get the actual labels from label string Input: label (string) : labels of the form '__label__2' Returns: label (int) : integer value corresponding to label string ''' return int(label.strip()[-1]) - 1 def get_pandas_df(self, filename): ''' Load the data into Pandas.DataFrame object This will be used to convert data to torchtext object ''' with open(filename, 'r') as datafile: data = [line.strip().split(',', maxsplit=1) for line in datafile] data_text = list(map(lambda x: x[1], data)) data_label = list(map(lambda x: self.parse_label(x[0]), data)) full_df = pd.DataFrame({"text":data_text, "label":data_label}) return full_df def load_data(self, train_file, test_file, val_file=None): ''' Loads the data from files Sets up iterators for training, validation and test data Also create vocabulary and word embeddings based on the data Inputs: train_file (String): absolute path to training file test_file (String): absolute path to test file val_file (String): absolute path to validation file ''' tokenizer = lambda sent: list(sent[::-1]) # Creating Field for data TEXT = data.Field(tokenize=tokenizer, lower=True, fix_length=self.config.seq_len) LABEL = data.Field(sequential=False, use_vocab=False) datafields = [("text",TEXT),("label",LABEL)] # Load data from pd.DataFrame into torchtext.data.Dataset train_df = self.get_pandas_df(train_file) train_examples = [data.Example.fromlist(i, datafields) for i in train_df.values.tolist()] train_data = data.Dataset(train_examples, datafields) test_df = self.get_pandas_df(test_file) test_examples = [data.Example.fromlist(i, datafields) for i in test_df.values.tolist()] test_data = data.Dataset(test_examples, datafields) # If validation file exists, load it. Otherwise get validation data from training data if val_file: val_df = self.get_pandas_df(val_file) val_examples = [data.Example.fromlist(i, datafields) for i in val_df.values.tolist()] val_data = data.Dataset(val_examples, datafields) else: train_data, val_data = train_data.split(split_ratio=0.9) TEXT.build_vocab(train_data) embedding_mat = get_embedding_matrix(list(TEXT.vocab.stoi.keys())) TEXT.vocab.set_vectors(TEXT.vocab.stoi, torch.FloatTensor(embedding_mat), len(TEXT.vocab.stoi)) self.vocab = TEXT.vocab self.embeddings = TEXT.vocab.vectors self.train_iterator = data.BucketIterator( (train_data), batch_size=self.config.batch_size, sort_key=lambda x: len(x.text), repeat=False, shuffle=True) self.val_iterator, self.test_iterator = data.BucketIterator.splits( (val_data, test_data), batch_size=self.config.batch_size, sort_key=lambda x: len(x.text), repeat=False, shuffle=False) print ("Loaded {} training examples".format(len(train_data))) print ("Loaded {} test examples".format(len(test_data))) print ("Loaded {} validation examples".format(len(val_data))) def evaluate_model(model, iterator): all_preds = [] all_y = [] for idx,batch in enumerate(iterator): if torch.cuda.is_available(): x = batch.text.cuda() else: x = batch.text y_pred = model(x) predicted = torch.max(y_pred.cpu().data, 1)[1] all_preds.extend(predicted.numpy()) all_y.extend(batch.label.numpy()) score = accuracy_score(all_y, np.array(all_preds).flatten()) return score
4,545
37.525424
103
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_CharCNN/model.py
# model.py import torch from torch import nn import numpy as np from utils import * class CharCNN(nn.Module): def __init__(self, config, vocab_size, embeddings): super(CharCNN, self).__init__() self.config = config embed_size = vocab_size # Embedding Layer self.embeddings = nn.Embedding(vocab_size, embed_size) self.embeddings.weight = nn.Parameter(embeddings, requires_grad=False) # This stackoverflow thread explains how conv1d works # https://stackoverflow.com/questions/46503816/keras-conv1d-layer-parameters-filters-and-kernel-size/46504997 conv1 = nn.Sequential( nn.Conv1d(in_channels=embed_size, out_channels=self.config.num_channels, kernel_size=7), nn.ReLU(), nn.MaxPool1d(kernel_size=3) ) # (batch_size, num_channels, (seq_len-6)/3) conv2 = nn.Sequential( nn.Conv1d(in_channels=self.config.num_channels, out_channels=self.config.num_channels, kernel_size=7), nn.ReLU(), nn.MaxPool1d(kernel_size=3) ) # (batch_size, num_channels, (seq_len-6-18)/(3*3)) conv3 = nn.Sequential( nn.Conv1d(in_channels=self.config.num_channels, out_channels=self.config.num_channels, kernel_size=3), nn.ReLU() ) # (batch_size, num_channels, (seq_len-6-18-18)/(3*3)) conv4 = nn.Sequential( nn.Conv1d(in_channels=self.config.num_channels, out_channels=self.config.num_channels, kernel_size=3), nn.ReLU() ) # (batch_size, num_channels, (seq_len-6-18-18-18)/(3*3)) conv5 = nn.Sequential( nn.Conv1d(in_channels=self.config.num_channels, out_channels=self.config.num_channels, kernel_size=3), nn.ReLU() ) # (batch_size, num_channels, (seq_len-6-18-18-18-18)/(3*3)) conv6 = nn.Sequential( nn.Conv1d(in_channels=self.config.num_channels, out_channels=self.config.num_channels, kernel_size=3), nn.ReLU(), nn.MaxPool1d(kernel_size=3) ) # (batch_size, num_channels, (seq_len-6-18-18-18-18-18)/(3*3*3)) # Length of output after conv6 conv_output_size = self.config.num_channels * ((self.config.seq_len - 96) // 27) linear1 = nn.Sequential( nn.Linear(conv_output_size, self.config.linear_size), nn.ReLU(), nn.Dropout(self.config.dropout_keep) ) linear2 = nn.Sequential( nn.Linear(self.config.linear_size, self.config.linear_size), nn.ReLU(), nn.Dropout(self.config.dropout_keep) ) linear3 = nn.Sequential( nn.Linear(self.config.linear_size, self.config.output_size), nn.Softmax() ) self.convolutional_layers = nn.Sequential(conv1,conv2,conv3,conv4,conv5,conv6) self.linear_layers = nn.Sequential(linear1, linear2, linear3) def forward(self, x): embedded_sent = self.embeddings(x).permute(1,2,0) # shape=(batch_size,embed_size,seq_len) conv_out = self.convolutional_layers(embedded_sent) conv_out = conv_out.view(conv_out.shape[0], -1) linear_output = self.linear_layers(conv_out) return linear_output def add_optimizer(self, optimizer): self.optimizer = optimizer def add_loss_op(self, loss_op): self.loss_op = loss_op def reduce_lr(self): print("Reducing LR") for g in self.optimizer.param_groups: g['lr'] = g['lr'] / 2 def run_epoch(self, train_iterator, val_iterator, epoch): train_losses = [] val_accuracies = [] losses = [] # Reduce learning rate as number of epochs increase if (epoch > 0) and (epoch % 3 == 0): self.reduce_lr() for i, batch in enumerate(train_iterator): self.optimizer.zero_grad() if torch.cuda.is_available(): x = batch.text.cuda() y = (batch.label).type(torch.cuda.LongTensor) else: x = batch.text y = (batch.label).type(torch.LongTensor) y_pred = self.__call__(x) loss = self.loss_op(y_pred, y) loss.backward() losses.append(loss.data.cpu().numpy()) self.optimizer.step() if i % 100 == 0: print("Iter: {}".format(i+1)) avg_train_loss = np.mean(losses) train_losses.append(avg_train_loss) print("\tAverage training loss: {:.5f}".format(avg_train_loss)) losses = [] # Evalute Accuracy on validation set val_accuracy = evaluate_model(self, val_iterator) print("\tVal Accuracy: {:.4f}".format(val_accuracy)) self.train() return train_losses, val_accuracies
5,019
40.147541
117
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_CharCNN/config.py
# config.py class Config(object): num_channels = 256 linear_size = 256 output_size = 4 max_epochs = 10 lr = 0.001 batch_size = 128 seq_len = 300 # 1014 in original paper dropout_keep = 0.5
221
19.181818
42
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_CharCNN/train.py
# train.py from utils import * from model import * from config import Config import sys import torch import torch.optim as optim from torch import nn if __name__=='__main__': config = Config() train_file = '../data/ag_news.train' if len(sys.argv) > 2: train_file = sys.argv[1] test_file = '../data/ag_news.test' if len(sys.argv) > 3: test_file = sys.argv[2] dataset = Dataset(config) dataset.load_data(train_file, test_file) # Create Model with specified optimizer and loss function ############################################################## model = CharCNN(config, len(dataset.vocab), dataset.embeddings) if torch.cuda.is_available(): model.cuda() model.train() optimizer = optim.Adam(model.parameters(), lr=config.lr) loss_fn = nn.CrossEntropyLoss() model.add_optimizer(optimizer) model.add_loss_op(loss_fn) ############################################################## train_losses = [] val_accuracies = [] for i in range(config.max_epochs): print ("Epoch: {}".format(i)) train_loss,val_accuracy = model.run_epoch(dataset.train_iterator, dataset.val_iterator, i) train_losses.append(train_loss) val_accuracies.append(val_accuracy) train_acc = evaluate_model(model, dataset.train_iterator) val_acc = evaluate_model(model, dataset.val_iterator) test_acc = evaluate_model(model, dataset.test_iterator) print ('Final Training Accuracy: {:.4f}'.format(train_acc)) print ('Final Validation Accuracy: {:.4f}'.format(val_acc)) print ('Final Test Accuracy: {:.4f}'.format(test_acc))
1,665
32.32
98
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_CharCNN/without_torchtext/utils.py
# utils.py import pandas as pd import numpy as np import torch from torch.utils.data import Dataset from torch.utils import data from torch.utils.data import DataLoader from torch.autograd import Variable from sklearn.metrics import accuracy_score # Used part of code to read the dataset from: https://github.com/1991viet/Character-level-cnn-pytorch/blob/master/src/dataset.py class MyDataset(Dataset): def __init__(self, data_path, config): self.config = config self.vocabulary = list("""abcdefghijklmnopqrstuvwxyz0123456789,;.!?:'\"/\\|_@#$%^&*~`+-=<>()[]{}""") self.identity_mat = np.identity(len(self.vocabulary)) data = get_pandas_df(data_path) self.texts = list(data.text) self.labels = list(data.label) self.length = len(self.labels) def __len__(self): return self.length def __getitem__(self, index): raw_text = self.texts[index] data = np.array([self.identity_mat[self.vocabulary.index(i)] for i in list(raw_text) if i in self.vocabulary], dtype=np.float32) if len(data) > self.config.max_len: data = data[:self.config.max_len] elif 0 < len(data) < self.config.max_len: data = np.concatenate( (data, np.zeros((self.config.max_len - len(data), len(self.vocabulary)), dtype=np.float32))) elif len(data) == 0: data = np.zeros((self.config.max_len, len(self.vocabulary)), dtype=np.float32) label = self.labels[index] return data, label def parse_label(label): ''' Get the actual labels from label string Input: label (string) : labels of the form '__label__2' Returns: label (int) : integer value corresponding to label string ''' return int(label.strip()[-1]) - 1 def get_pandas_df(filename): ''' Load the data into Pandas.DataFrame object This will be used to convert data to torchtext object ''' with open(filename, 'r') as datafile: data = [line.strip().split(',', maxsplit=1) for line in datafile] data_text = list(map(lambda x: x[1], data)) data_label = list(map(lambda x: parse_label(x[0]), data)) full_df = pd.DataFrame({"text":data_text, "label":data_label}) return full_df def get_iterators(config, train_file, test_file, val_file=None): train_set = MyDataset(train_file, config) test_set = MyDataset(test_file, config) # If validation file exists, load it. Otherwise get validation data from training data if val_file: val_set = MyDataset(val_file, config) else: train_size = int(0.9 * len(train_set)) test_size = len(train_set) - train_size train_set, val_set = data.random_split(train_set, [train_size, test_size]) train_iterator = DataLoader(train_set, batch_size=config.batch_size, shuffle=True) test_iterator = DataLoader(test_set, batch_size=config.batch_size) val_iterator = DataLoader(val_set, batch_size=config.batch_size) return train_iterator, test_iterator, val_iterator def evaluate_model(model, iterator): all_preds = [] all_y = [] for idx,batch in enumerate(iterator): if torch.cuda.is_available(): batch = [Variable(record).cuda() for record in batch] else: batch = [Variable(record).cuda() for record in batch] x, y = batch y_pred = model(x) predicted = torch.max(y_pred.cpu().data, 1)[1] all_preds.extend(predicted.numpy()) all_y.extend(y.cpu().numpy()) score = accuracy_score(all_y, np.array(all_preds).flatten()) return score
3,657
37.505263
128
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_CharCNN/without_torchtext/model.py
# model.py import torch from torch import nn import numpy as np from torch.autograd import Variable from utils import * class CharCNN(nn.Module): def __init__(self, config): super(CharCNN, self).__init__() self.config = config # This stackoverflow thread explains how conv1d works # https://stackoverflow.com/questions/46503816/keras-conv1d-layer-parameters-filters-and-kernel-size/46504997 conv1 = nn.Sequential( nn.Conv1d(in_channels=self.config.vocab_size, out_channels=self.config.num_channels, kernel_size=7), nn.ReLU(), nn.MaxPool1d(kernel_size=3) ) # (batch_size, num_channels, (max_len-6)/3) conv2 = nn.Sequential( nn.Conv1d(in_channels=self.config.num_channels, out_channels=self.config.num_channels, kernel_size=7), nn.ReLU(), nn.MaxPool1d(kernel_size=3) ) # (batch_size, num_channels, (max_len-6-18)/(3*3)) conv3 = nn.Sequential( nn.Conv1d(in_channels=self.config.num_channels, out_channels=self.config.num_channels, kernel_size=3), nn.ReLU() ) # (batch_size, num_channels, (max_len-6-18-18)/(3*3)) conv4 = nn.Sequential( nn.Conv1d(in_channels=self.config.num_channels, out_channels=self.config.num_channels, kernel_size=3), nn.ReLU() ) # (batch_size, num_channels, (max_len-6-18-18-18)/(3*3)) conv5 = nn.Sequential( nn.Conv1d(in_channels=self.config.num_channels, out_channels=self.config.num_channels, kernel_size=3), nn.ReLU() ) # (batch_size, num_channels, (max_len-6-18-18-18-18)/(3*3)) conv6 = nn.Sequential( nn.Conv1d(in_channels=self.config.num_channels, out_channels=self.config.num_channels, kernel_size=3), nn.ReLU(), nn.MaxPool1d(kernel_size=3) ) # (batch_size, num_channels, (max_len-6-18-18-18-18-18)/(3*3*3)) # Length of output after conv6 conv_output_size = self.config.num_channels * ((self.config.max_len - 96) // 27) linear1 = nn.Sequential( nn.Linear(conv_output_size, self.config.linear_size), nn.ReLU(), nn.Dropout(self.config.dropout_keep) ) linear2 = nn.Sequential( nn.Linear(self.config.linear_size, self.config.linear_size), nn.ReLU(), nn.Dropout(self.config.dropout_keep) ) linear3 = nn.Sequential( nn.Linear(self.config.linear_size, self.config.output_size), nn.Softmax() ) self.convolutional_layers = nn.Sequential(conv1,conv2,conv3,conv4,conv5,conv6) self.linear_layers = nn.Sequential(linear1, linear2, linear3) # Initialize Weights self._create_weights(mean=0.0, std=0.05) def _create_weights(self, mean=0.0, std=0.05): for module in self.modules(): if isinstance(module, nn.Conv1d) or isinstance(module, nn.Linear): module.weight.data.normal_(mean, std) def forward(self, embedded_sent): embedded_sent = embedded_sent.transpose(1,2)#.permute(0,2,1) # shape=(batch_size,embed_size,max_len) conv_out = self.convolutional_layers(embedded_sent) conv_out = conv_out.view(conv_out.shape[0], -1) linear_output = self.linear_layers(conv_out) return linear_output def add_optimizer(self, optimizer): self.optimizer = optimizer def add_loss_op(self, loss_op): self.loss_op = loss_op def reduce_lr(self): print("Reducing LR") for g in self.optimizer.param_groups: g['lr'] = g['lr'] / 2 def run_epoch(self, train_iterator, val_iterator, epoch): train_losses = [] val_accuracies = [] losses = [] # Reduce learning rate as number of epochs increase if (epoch > 0 and epoch%3 == 0): self.reduce_lr() for i, batch in enumerate(train_iterator): _, n_true_label = batch if torch.cuda.is_available(): batch = [Variable(record).cuda() for record in batch] else: batch = [Variable(record) for record in batch] x, y = batch self.optimizer.zero_grad() y_pred = self.__call__(x) loss = self.loss_op(y_pred, y) loss.backward() losses.append(loss.data.cpu().numpy()) self.optimizer.step() if i % 100 == 0: self.eval() print("Iter: {}".format(i+1)) avg_train_loss = np.mean(losses) train_losses.append(avg_train_loss) print("\tAverage training loss: {:.5f}".format(avg_train_loss)) losses = [] # Evalute Accuracy on validation set val_accuracy = evaluate_model(self, val_iterator) print("\tVal Accuracy: {:.4f}".format(val_accuracy)) self.train() return train_losses, val_accuracies
5,218
39.773438
117
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_CharCNN/without_torchtext/config.py
# config.py class Config(object): num_channels = 256 linear_size = 256 output_size = 4 max_epochs = 10 lr = 0.001 batch_size = 128 vocab_size = 68 max_len = 300 # 1014 in original paper dropout_keep = 0.5
241
19.166667
42
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_CharCNN/without_torchtext/train.py
# train.py from utils import * from model import * from config import Config import sys import torch import torch.optim as optim from torch import nn if __name__=='__main__': config = Config() train_file = '../data/ag_news.train' if len(sys.argv) > 2: train_file = sys.argv[1] test_file = '../data/ag_news.test' if len(sys.argv) > 3: test_file = sys.argv[2] train_iterator, test_iterator, val_iterator = get_iterators(config, train_file, test_file) # Create Model with specified optimizer and loss function ############################################################## model = CharCNN(config) if torch.cuda.is_available(): model.cuda() model.train() optimizer = optim.Adam(model.parameters(), lr=config.lr) loss_fn = nn.CrossEntropyLoss() model.add_optimizer(optimizer) model.add_loss_op(loss_fn) ############################################################## train_losses = [] val_accuracies = [] for i in range(config.max_epochs): print ("Epoch: {}".format(i)) train_loss,val_accuracy = model.run_epoch(train_iterator, val_iterator, i) train_losses.append(train_loss) val_accuracies.append(val_accuracy) train_acc = evaluate_model(model, train_iterator) val_acc = evaluate_model(model, val_iterator) test_acc = evaluate_model(model, test_iterator) print ('Final Training Accuracy: {:.4f}'.format(train_acc)) print ('Final Validation Accuracy: {:.4f}'.format(val_acc)) print ('Final Test Accuracy: {:.4f}'.format(test_acc))
1,605
31.77551
94
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_fastText/utils.py
# utils.py import torch from torchtext import data from torchtext.vocab import Vectors import spacy import pandas as pd import numpy as np from sklearn.metrics import accuracy_score class Dataset(object): def __init__(self, config): self.config = config self.train_iterator = None self.test_iterator = None self.val_iterator = None self.vocab = [] self.word_embeddings = {} def parse_label(self, label): ''' Get the actual labels from label string Input: label (string) : labels of the form '__label__2' Returns: label (int) : integer value corresponding to label string ''' return int(label.strip()[-1]) def get_pandas_df(self, filename): ''' Load the data into Pandas.DataFrame object This will be used to convert data to torchtext object ''' with open(filename, 'r') as datafile: data = [line.strip().split(',', maxsplit=1) for line in datafile] data_text = list(map(lambda x: x[1], data)) data_label = list(map(lambda x: self.parse_label(x[0]), data)) full_df = pd.DataFrame({"text":data_text, "label":data_label}) return full_df def load_data(self, w2v_file, train_file, test_file, val_file=None): ''' Loads the data from files Sets up iterators for training, validation and test data Also create vocabulary and word embeddings based on the data Inputs: w2v_file (String): absolute path to file containing word embeddings (GloVe/Word2Vec) train_file (String): absolute path to training file test_file (String): absolute path to test file val_file (String): absolute path to validation file ''' NLP = spacy.load('en') tokenizer = lambda sent: [x.text for x in NLP.tokenizer(sent) if x.text != " "] # Creating Field for data TEXT = data.Field(sequential=True, tokenize=tokenizer, lower=True) LABEL = data.Field(sequential=False, use_vocab=False) datafields = [("text",TEXT),("label",LABEL)] # Load data from pd.DataFrame into torchtext.data.Dataset train_df = self.get_pandas_df(train_file) train_examples = [data.Example.fromlist(i, datafields) for i in train_df.values.tolist()] train_data = data.Dataset(train_examples, datafields) test_df = self.get_pandas_df(test_file) test_examples = [data.Example.fromlist(i, datafields) for i in test_df.values.tolist()] test_data = data.Dataset(test_examples, datafields) # If validation file exists, load it. Otherwise get validation data from training data if val_file: val_df = self.get_pandas_df(val_file) val_examples = [data.Example.fromlist(i, datafields) for i in val_df.values.tolist()] val_data = data.Dataset(val_examples, datafields) else: train_data, val_data = train_data.split(split_ratio=0.8) TEXT.build_vocab(train_data, vectors=Vectors(w2v_file)) self.word_embeddings = TEXT.vocab.vectors self.vocab = TEXT.vocab self.train_iterator = data.BucketIterator( (train_data), batch_size=self.config.batch_size, sort_key=lambda x: len(x.text), repeat=False, shuffle=True) self.val_iterator, self.test_iterator = data.BucketIterator.splits( (val_data, test_data), batch_size=self.config.batch_size, sort_key=lambda x: len(x.text), repeat=False, shuffle=False) print ("Loaded {} training examples".format(len(train_data))) print ("Loaded {} test examples".format(len(test_data))) print ("Loaded {} validation examples".format(len(val_data))) def evaluate_model(model, iterator): all_preds = [] all_y = [] for idx,batch in enumerate(iterator): if torch.cuda.is_available(): x = batch.text.cuda() else: x = batch.text y_pred = model(x) predicted = torch.max(y_pred.cpu().data, 1)[1] + 1 all_preds.extend(predicted.numpy()) all_y.extend(batch.label.numpy()) score = accuracy_score(all_y, np.array(all_preds).flatten()) return score
4,462
37.145299
97
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_fastText/model.py
# model.py import torch from torch import nn import numpy as np from utils import * class fastText(nn.Module): def __init__(self, config, vocab_size, word_embeddings): super(fastText, self).__init__() self.config = config # Embedding Layer self.embeddings = nn.Embedding(vocab_size, self.config.embed_size) self.embeddings.weight = nn.Parameter(word_embeddings, requires_grad=False) # Hidden Layer self.fc1 = nn.Linear(self.config.embed_size, self.config.hidden_size) # Output Layer self.fc2 = nn.Linear(self.config.hidden_size, self.config.output_size) # Softmax non-linearity self.softmax = nn.Softmax() def forward(self, x): embedded_sent = self.embeddings(x).permute(1,0,2) h = self.fc1(embedded_sent.mean(1)) z = self.fc2(h) return self.softmax(z) def add_optimizer(self, optimizer): self.optimizer = optimizer def add_loss_op(self, loss_op): self.loss_op = loss_op def reduce_lr(self): print("Reducing LR") for g in self.optimizer.param_groups: g['lr'] = g['lr'] / 2 def run_epoch(self, train_iterator, val_iterator, epoch): train_losses = [] val_accuracies = [] losses = [] # Reduce learning rate as number of epochs increase if (epoch == int(self.config.max_epochs/3)) or (epoch == int(2*self.config.max_epochs/3)): self.reduce_lr() for i, batch in enumerate(train_iterator): self.optimizer.zero_grad() if torch.cuda.is_available(): x = batch.text.cuda() y = (batch.label - 1).type(torch.cuda.LongTensor) else: x = batch.text y = (batch.label - 1).type(torch.LongTensor) y_pred = self.__call__(x) loss = self.loss_op(y_pred, y) loss.backward() losses.append(loss.data.cpu().numpy()) self.optimizer.step() if i % 100 == 0: print("Iter: {}".format(i+1)) avg_train_loss = np.mean(losses) train_losses.append(avg_train_loss) print("\tAverage training loss: {:.5f}".format(avg_train_loss)) losses = [] # Evalute Accuracy on validation set val_accuracy = evaluate_model(self, val_iterator) print("\tVal Accuracy: {:.4f}".format(val_accuracy)) self.train() return train_losses, val_accuracies
2,709
33.74359
98
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_fastText/config.py
# config.py class Config(object): embed_size = 300 hidden_size = 10 output_size = 4 max_epochs = 30 lr = 0.5 batch_size = 128
150
15.777778
21
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_fastText/train.py
# train.py from utils import * from model import * from config import Config import numpy as np import sys import torch.optim as optim from torch import nn import torch if __name__=='__main__': config = Config() train_file = '../data/ag_news.train' if len(sys.argv) > 2: train_file = sys.argv[1] test_file = '../data/ag_news.test' if len(sys.argv) > 3: test_file = sys.argv[2] w2v_file = '../data/glove.840B.300d.txt' dataset = Dataset(config) dataset.load_data(w2v_file, train_file, test_file) # Create Model with specified optimizer and loss function ############################################################## model = fastText(config, len(dataset.vocab), dataset.word_embeddings) if torch.cuda.is_available(): model.cuda() model.train() optimizer = optim.SGD(model.parameters(), lr=config.lr) NLLLoss = nn.NLLLoss() model.add_optimizer(optimizer) model.add_loss_op(NLLLoss) ############################################################## train_losses = [] val_accuracies = [] for i in range(config.max_epochs): print ("Epoch: {}".format(i)) train_loss,val_accuracy = model.run_epoch(dataset.train_iterator, dataset.val_iterator, i) train_losses.append(train_loss) val_accuracies.append(val_accuracy) train_acc = evaluate_model(model, dataset.train_iterator) val_acc = evaluate_model(model, dataset.val_iterator) test_acc = evaluate_model(model, dataset.test_iterator) print ('Final Training Accuracy: {:.4f}'.format(train_acc)) print ('Final Validation Accuracy: {:.4f}'.format(val_acc)) print ('Final Test Accuracy: {:.4f}'.format(test_acc))
1,740
31.849057
98
py
Text-Classification-Models-Pytorch
Text-Classification-Models-Pytorch-master/Model_fastText/old_code/utils.py
# utils.py from nltk import word_tokenize from tqdm import tqdm from gensim.models import KeyedVectors import numpy as np import math class Vocab(object): def __init__(self): self.word_to_index = {} self.index_to_word = {} self.unknown = '<unk>' self.add_word(self.unknown) def add_word(self, word): ''' Add a word to the vocabulary Inputs: word (string) : Word to be added to vocabulary ''' if word not in self.word_to_index: index = len(self.word_to_index) self.word_to_index[word] = index self.index_to_word[index] = word def construct(self, words): ''' Construct the vocabulary Inputs: words (list[string]) : List of words defining the vocabulary ''' for word in words: self.add_word(word) print ("Constructed vocabulary of size: {}".format(len(self.word_to_index))) def encode(self, word): ''' Given a word, get corresponding index in vocabulary. ''' if word not in self.word_to_index: word = self.unknown return self.word_to_index(word) def decode(self, index): ''' Given a word index, get corresponding word from vocabulary. ''' return self.index_to_word(index) def __len__(self): return len(self.word_to_index) def parse_label(label): ''' Get the actual labels from label string Input: label (string) : labels of the form '__label__2' Returns: label (int) : integer value corresponding to label string ''' return int(label.strip()[-1]) def get_data(filename): ''' Loads the data from file Inputs: filename (String): absolute path to the datafile Returns: X (list[string]): list of contents of documents y (list[integer]): labels of documents vocab : Vocab object corresponding to words in X ''' print ('Reading data from {}'.format(filename)) with open(filename, 'r') as datafile: data = [line.strip().split(',', maxsplit=1) for line in datafile] data_text = list(map(lambda x: x[1], data)) data_label = list(map(lambda x: parse_label(x[0]), data)) vocab = Vocab() words = set(' '.join(data_text).lower().split()) vocab.construct(list(words)) return data_text, data_label, vocab def get_word_embeddings(w2vfile, word_to_index, embedsize=300): ''' For each word in our vocabulary, get the word2vec encoding of the word Inputs: w2vfile (string) : Path to the file containing (pre-trained) word embeddings embedsize (int) : Length of each word vector Returns: word_embeddings : Dictionary mapping each word to corresponding embedding ''' word_embeddings = {} if w2vfile.endswith('.txt'): f = open(w2vfile) for line in tqdm(f): values = line.split(" ") word = values[0] coefs = np.asarray(values[1:], dtype='float32') if word in word_to_index: word_embeddings[word] = coefs f.close() elif w2vfile.endswith('.bin'): word2vec = KeyedVectors.load_word2vec_format(w2vfile, binary=True, limit=1000000) for word in tqdm(word_to_index): try: word_embeddings[word] = word2vec[word.lower()] except KeyError: pass else: print ('Can\'t load word embeddings.') exit(-1) print('Found {0}/{1} word vectors.'.format(len(word_embeddings), len(word_to_index))) if len(word_to_index) > len(word_embeddings): print('Initializing remaining {} word vectors with zeros.'.format(len(word_to_index) - len(word_embeddings))) for word in word_to_index: if word not in word_embeddings: word_embeddings[word] = np.zeros((embedsize,)) return word_embeddings def encode_text(text, word_embeddings): ''' Encode a sequence of words into corresponding vector representation Input: text (string) : text (space separated words, etc..) word_embeddings (dict) : dictionary mapping from words to their representation max_sent_len (int) : maximum sentence length (in words) Returns: X (np.array) : array of shape (embedding_size,) averaging all word vectors of text ''' embed = np.zeros(300) count = 0 words = word_tokenize(text) for word in words: if word in word_embeddings: embed += word_embeddings[word] count += 1 return embed / count def data_iterator(train_x, train_y, batch_size = 256): ''' Generate batches of training data for training (for single epoch) Inputs: train_df (pd.DataFrame) : complete training data batch_size (int) : Size of each batch Returns: text_arr (np.matrix) : Matrix of shape (batch_size,embed_size) lebel_arr (np.array) : Labels of this batch. Array of shape (batch_size,) ''' n_batches = math.ceil(len(train_x) / batch_size) for idx in range(n_batches): x = train_x[idx *batch_size:(idx+1) * batch_size] y = train_y[idx *batch_size:(idx+1) * batch_size] yield x, y
5,339
32.797468
117
py