0%

基本类型复制

有时会遇到源proto和目标proto具有相同成员的情况, 如果该成员仅仅是定义相同,是不能直接使用CopyFrom方法的,此时需要手动对结构体成员依次进行赋值。
以下文件模拟了两个不同proto文件中同时定义了相同的结构体Feature

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
message ProtoSrc
{
message Feature
{
repeated float data = 1;
}
optional Feature feature = 1;
}
message ProtoDst
{
message Feature
{
repeated float data = 1;
}
optional Feature feature = 1;
}
1
2
3
4
5
6
7
8
auto src = ProtoSrc();
auto dst = ProtoDst();
auto srcFeature = src.feature();
auto &dstFeature = *dst.mutable_feature();
// 👇错误操作,会有类似报错: Tried to merge messages of different types (merge protosrc.Feature to protodst.Feature)
// dstFeature.CopyFrom(srcFeature);
// 👇正确操作
dstFeature.mutable_data()->CopyFrom(srcFeature.data());

复杂类型复制

以下文件模拟了两个不同proto文件中同时定义了相同的结构体Result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
message ProtoSrc
{
message Result
{
optional float data = 1;
}
repeated Result results = 1;
}
message ProtoDst
{
message Result
{
optional float data = 1;
}
repeated Result results = 1;
}
1
2
3
4
5
6
7
auto src = ProtoSrc();
auto dst = ProtoDst();
auto &dstRes = *(dst.mutable_results());
for (auto &srcRes : *(src.mutable_results())){
auto &temp = *(dstRes.Add());
temp.set_data(srcRes.data());
}

文件流式处理

在处理hdfs数据时,可能会遇到本地磁盘空间不足以存放数据的问题,这时我们可以使用linux的stdio对数据进行流式处理,以替换每行内容为例

1
2
3
hadoop -cat hdfs://your_path/your_file |\
sed "s/some_thing/some_other/g" |\
hadoop -put - hdfs://your_path/your_processed_file

这样利用pipe完成了对数据的处理,同时避免了数据在本地落盘。

遍历文件夹处理

此外还可以搭配xargs遍历整个目录

  • hadoop -ls -h hdfs://your_path 列出整个目录
  • awk -F' ' '{print $NF}' 取出最后一列,也就是文件地址列
  • awk -F'/' '{print $NF}' 将地址中的文件名取出
  • xargs -I {} bash -c ... 将每个文件名依次作为参数处理
  • "hadoop -cat ..." 按照之前流式处理的方式处理每一个文件
1
hadoop -ls -h hdfs://your_path | awk -F' ' '{print $NF}' | awk -F'/' '{print $NF}' | xargs -I {} bash -c "hadoop -cat hdfs://your_path/{} | sed 's/some_thing/some_other/g' | hadoop -put - hdfs://your_other_path/{}"

最近看到知乎上,关于最让自己印象深刻的一次bug的经历,的讨论,不禁让我回想起了研一时,那一次libc依赖损坏的事故。

阅读全文 »

在部署模型时,对于输入数据的预处理是一个非常耗时的操作,其实可以将预处理一同打包到模型中,在转换为ONNX或者Tensorrt模型后这些操作就可以随着模型一起被加速执行。

以最简单的归一化操作为例

归一化Module如下:

1
2
3
4
5
6
7
8
9
class Normalize(torch.nn.Module):
def __init__(self):
super().__init__()
self.register_buffer('mean', torch.tensor([0.485, 0.456, 0.406], dtype=torch.float64).view(1, -1, 1, 1))
self.register_buffer('std', torch.tensor([0.229, 0.224, 0.225], dtype=torch.float64).view(1, -1, 1, 1))
self.register_buffer('norm', torch.tensor([255.0], dtype=torch.float64).view(1, 1, 1, 1))

def forward(self, images):
return (images / self.norm - self.mean) / self.std

之后修改模型的inti和forward函数即可

1
2
3
4
5
6
7
8
9
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
# ... other code
self.normalize = Normalize()

def forward(self, x):
x = self.normalize(x)
# ... other code

有时我们无法确定一段代码会抛出何种异常,但是又希望能捕获这些异常

阅读全文 »