MNN Session 之几何计算(六)

简介: MNN Session 之几何计算(六)

1、createSession

    依据 ScheduleConfig 和 RuntimeInfo 创建会话。

// source/core/Interpreter.cpp
Session* Interpreter::createSession(const ScheduleConfig& config, const RuntimeInfo& runtime) {
    return createMultiPathSession({config}, runtime);
}

1.1 createMultiPathSession

createMultiPathSession 完整代码

// source/core/Interpreter.cpp
Session* Interpreter::createMultiPathSession(const std::vector<ScheduleConfig>& configs, const RuntimeInfo& runtime) {
  // ...
    auto result = newSession.get();
    auto validForResize = info.validForResize;
    if (validForResize && mNet->modes.inputMode == Session_Input_Inside && mNet->modes.resizeMode == Session_Resize_Direct) {
        result->resize();
    }
    // ...
    return result;
}

1.1.1 Session::resize

Session::resize 完整代码

// source/core/Session.cpp
ErrorCode Session::resize() {
  // ...
    if (mNeedResize) {
        bool debug = mCallBackMode == Interpreter::Session_Debug;
        // mPipelines 类型为 std::vector<std::shared_ptr<Pipeline>>
        for (auto& iter : mPipelines) {
            auto error = iter->encode(debug, permitCodegen);
            if (NO_ERROR != error) {
                return error;
            }
        }
        mNeedResize = false;
        mNeedMalloc = true;
        firstMalloc = true;
    }
    // ...
}

1.1.1.1 Pipeline::encode

Pipeline::encode 完整代码

BackendCache、OpCacheInfo

// source/core/Pipeline.cpp
// typedef std::pair<BackendCache, std::vector<OpCacheInfo>> PipelineInfo;
//
//   struct BackendCache {
//      Backend::Info info;
//      BackendConfig config;
//      std::pair<std::shared_ptr<Backend>, std::shared_ptr<Backend>> cache;
//      bool needComputeShape = true;
//      bool needComputeGeometry = true;
//      bool reportError = true;
//      std::map<Tensor*, TENSORCACHE> inputTensorCopyCache;
//  };
//
//    /** pipeline info */
//    struct OpCacheInfo {
//        /** op */
//        const Op* op;
//        /** input tensors */
//        std::vector<Tensor*> inputs;
//        /** output tensors */
//        std::vector<Tensor*> outputs;
//        /** schedule type*/
//        Schedule::Type type = Schedule::Type::SEPARATE;
//
//        /**Command buffer for cache*/
//        CommandBuffer cacheBuffer;
//
//        /**Command buffer for execute*/
//        CommandBuffer executeBuffer;
//        
//        std::map<const Op*, std::shared_ptr<Execution>> executionCache;
//    };
//
ErrorCode Pipeline::encode(bool supportDebug, bool permitCodegen) {
  // mInfo.first.cache 类型为 std::pair<std::shared_ptr<Backend>, std::shared_ptr<Backend>>
  // mBackend 创建的后端如(VulkanBackend)
    auto& mBackend = mInfo.first.cache.first;
    // mBackupBackend 创建的后备(默认)后端如(CPUBackend)
    auto& mBackupBackend = mInfo.first.cache.second;
    // Static Model just copy info to command buffer
    // mInfo.first 类型为 BackendCache 
    if (!mInfo.first.needComputeGeometry) {
        // ...
    } else {
#ifndef MNN_BUILD_MINI
    // mContext 类型为 GeometryComputer::Context
        mContext.clear();
        /** Size Compute and compute Const Begin */
        auto res = GeometryComputerUtils::shapeComputeAndGeometryTransform(mInfo.second, mContext, mInfo.first.cache.second, mUseGeometry, false, permitCodegen);
        if (res != NO_ERROR) {
            return res;
        }
#endif
    }
  // ...
    return NO_ERROR;
}

1.1.1.1.1 GeometryComputerUtils::shapeComputeAndGeometryTransform

GeometryComputerUtils::shapeComputeAndGeometryTransform 完整代码

OpCacheInfo

// source/geometry/GeometryComputerUtils.cpp
//    /** pipeline info */
//    struct OpCacheInfo {
//        /** op */
//        const Op* op;
//        /** input tensors */
//        std::vector<Tensor*> inputs;
//        /** output tensors */
//        std::vector<Tensor*> outputs;
//        /** schedule type*/
//        Schedule::Type type = Schedule::Type::SEPARATE;
//
//        /**Command buffer for cache*/
//        CommandBuffer cacheBuffer;
//
//        /**Command buffer for execute*/
//        CommandBuffer executeBuffer;
//        
//        std::map<const Op*, std::shared_ptr<Execution>> executionCache;
//    };
//
ErrorCode GeometryComputerUtils::shapeComputeAndGeometryTransform(
    std::vector<Schedule::OpCacheInfo>& infos,
    GeometryComputer::Context& geoContext,
    std::shared_ptr<Backend> backupBackend,
    Runtime::CompilerType compileType, 
    bool skipShapeCompute,
    bool permitCodegen) {
    /** Size Compute and compute Const Begin */
    GeometryComputer::Context ctx(backupBackend);
    // Size Compute and compute Const
    // infos 为算子缓存,大小为 171
    for (int i=0; i<infos.size(); ++i) {
      // info 类型为 OpCacheInfo
        auto& info = infos[i];
        auto& cmdBufferVir = info.executeBuffer;
        auto& tempBuffer = info.cacheBuffer;
    // ...
        if (info.type == Schedule::CONSTANT) {
            if (_hasZeroShapeOutput(info)) {
                continue;
            }
            ctx.clear();
            auto geo = GeometryComputer::search(info.op->type(), Runtime::Compiler_Loop);
            {
                auto res = geo->onRecompute(info.op, info.inputs, info.outputs, geoContext, tempBuffer);
                if (!res) {
                    tempBuffer.command.clear();
                    tempBuffer.extras.clear();
                    res = geo->onCompute(info.op, info.inputs, info.outputs, geoContext, tempBuffer);
                }
                if (!res) {
                    MNN_ERROR("Const Folder Error in geometry for %s\n", info.op->name()->c_str());
                    return NOT_SUPPORT;
                }
            }
            GeometryComputerUtils::makeRaster(tempBuffer, cmdBufferVir, ctx);
            for (auto t : info.outputs) {
                ctx.getRasterCacheCreateRecursive(t, cmdBufferVir);
            }
            // ...
        }
    }
    /** Size Compute and compute Const End */

    /** Geometry Transform */
    for (int i=0; i<infos.size(); ++i) {
        auto& info = infos[i];
        auto& cmdBufferReal = info.executeBuffer;
        auto& tempBuffer = info.cacheBuffer;
        // TODO: Optimize
        if (info.type == Schedule::CONSTANT) {
            continue;
        }
        if (_hasZeroShapeOutput(info)) {
            continue;
        }
        auto geo = GeometryComputer::search(info.op->type(), compileType);
        {
            bool res = false;
            if (!tempBuffer.hasWrap) {
                res = geo->onRecompute(info.op, info.inputs, info.outputs, geoContext, tempBuffer);
            }
            if (!res) {
                tempBuffer.command.clear();
                tempBuffer.extras.clear();
                res = geo->onCompute(info.op, info.inputs, info.outputs, geoContext, tempBuffer);
            }
            if (!res) {
                return NOT_SUPPORT;
            }
            tempBuffer.hasWrap = false;
            GeometryComputerUtils::makeRaster(tempBuffer, cmdBufferReal, geoContext);
            for (auto t : info.outputs) {
                auto des = TensorUtils::getDescribe(t);
                if (des->usage == Tensor::InsideDescribe::OUTPUT || des->usage == Tensor::InsideDescribe::TRAINABLE) {
                    // For output and trainable value, must directly compute the tensor
                    geoContext.getRasterCacheCreateRecursive(t, cmdBufferReal);
                }
            }
        }
    }
  // ...
    return NO_ERROR;
}

1.1.1.1.1.1 GeometryComputer::search

// source/geometry/GeometryComputer.cpp
const GeometryComputer* GeometryComputer::search(int type, Runtime::CompilerType compType) {
    return GeometryComputerManager::get()->search(type, compType);
}

1.1.1.1.1.1.1 GeometryComputerManager::search

// source/geometry/GeometryComputer.cpp
    GeometryComputer* search(int type, Runtime::CompilerType compType) {
        if (Runtime::Compiler_Origin == compType) {
            return &mDefault;
        }
        if (Runtime::Compiler_Loop == compType) {
            auto iter = mLoopTable[type].get();
            if (iter != nullptr) {
                return iter;
            }
        }
        // Geometry
        auto iter = mTable[type].get();
        if (iter != nullptr) {
            // FUNC_PRINT(type);
            return iter;
        }
        return &mDefault;
    }

1.1.1.1.1.1.1.1 几何计算初始化

    几何计算初始化与维度计算初始化类似,其在 registerBackend 函数中调用 GeometryComputer::init() 来实现的。

static std::once_flag s_flag;
void registerBackend() {
    std::call_once(s_flag, [&]() {
    // ...
        SizeComputerSuite::init();
        GeometryComputer::init();
    // ...        
    });
}

    GeometryComputer::init() 实现如下:

// source/geometry/GeometryComputer.cpp
void GeometryComputer::init() {
    if (nullptr == GeometryComputerManager::get()) {
        GeometryComputerManager::init();
        registerGeometryOps();
    }
}

class GeometryComputerManager {
    static void init() {
        gInstance = new GeometryComputerManager;
        gInstance->mTable.resize(OpType_MAX + 1);
        gInstance->mLoopTable.resize(OpType_MAX + 1);
    }
}    

    registerGeometryOps 实现如下:

// source/geometry/GeometryOPRegister.cpp
void registerGeometryOps() {
___GeometryShape___create__();
___GeometryPermute___create__();
  // ...
}

  函数 ___GeometryShape___create__ 是通过 REGISTER_GEOMETRY 宏定义的:

// source/geometry/GeometryComputer.hpp
#define REGISTER_GEOMETRY(f, c)       \
    extern void ___##f##__##c##__() { \
        c();                          \
    }

    其实现代码如下:

// source/geometry/GeometryShape.cpp
class GeometryShape : public GeometryComputer {
public:
    virtual bool onCompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs,
                           Context& context, CommandBuffer& res) const override {
        if (nullptr == TensorUtils::getDescribe(outputs[0])->mem.get()) {
            auto originSize = outputs[0]->length(0);
            outputs[0]->setLength(0, MNN_MAX_TENSOR_DIM);
            if(!context.allocTensor(outputs[0])) {
                return false;
            }
            outputs[0]->setLength(0, originSize);
        }
        auto& ib         = inputs[0]->buffer();
        auto outputData = outputs[0]->host<int>();
        auto inputFormat = TensorUtils::getDescribe(inputs[0])->dimensionFormat;
        if ((inputFormat == MNN_DATA_FORMAT_NC4HW4) && TensorUtils::getDescribe(outputs[0])->dimensionFormat == MNN_DATA_FORMAT_NHWC) {
            outputData[0] = ib.dim[0].extent;
            outputData[1] = ib.dim[2].extent;
            outputData[2] = ib.dim[3].extent;
            outputData[3] = ib.dim[1].extent;
        } else {
            for (int i = 0; i < ib.dimensions; i++) {
                outputData[i] = ib.dim[i].extent;
            }
        }
        return true;
    }
};

class GeometryRank : public GeometryComputer {
  // ...
}

class GeometryPriorBox : public GeometryComputer {
  // ...
}

class GeometrySize : public GeometryComputer {
  // ...
}

class GeometryRaster : public GeometryComputer {
  // ...
}

static void _create() {
    // ...
}

REGISTER_GEOMETRY(GeometryShape, _create);

    REGISTER_GEOMETRY(GeometryShape, _create) 宏扩展如下:

// REGISTER_GEOMETRY(GeometryShape, _create)
    extern void ___GeometryShape___create__() {
        _create();                         
    }

  _create 函数的实现代码如下:

// source/geometry/GeometryShape.cpp
static void _create() {
    std::shared_ptr<GeometryComputer> comp(new GeometryShape);
    GeometryComputer::registerGeometryComputer(comp, {OpType_Shape});
    std::shared_ptr<GeometryComputer> comp1(new GeometryRank);
    GeometryComputer::registerGeometryComputer(comp1, {OpType_Rank});
    std::shared_ptr<GeometryComputer> comp2(new GeometryPriorBox);
    GeometryComputer::registerGeometryComputer(comp2, {OpType_PriorBox});
    std::shared_ptr<GeometryComputer> comp3(new GeometrySize);
    GeometryComputer::registerGeometryComputer(comp3, {OpType_Size});
    std::shared_ptr<GeometryComputer> comp4(new GeometryRaster);
    GeometryComputer::registerGeometryComputer(comp4, {OpType_Raster});
}

    _create 函数依次新建并注册了 GeometryShape、GeometryRank、GeometryPriorBox、GeometrySize、GeometryRaster 。注册是通过函数

GeometryComputer::registerGeometryComputer 实现的,其实现如下:

// source/geometry/GeometryComputer.cpp
void GeometryComputer::registerGeometryComputer(std::shared_ptr<GeometryComputer> comp, std::vector<int> type, Runtime::CompilerType compType) {
    auto ins = GeometryComputerManager::get();
    for (auto t : type) {
        ins->insert(comp, t, compType);
    }
}

class GeometryComputerManager {
    void insert(std::shared_ptr<GeometryComputer> c, int type, Runtime::CompilerType compType) {
        if (Runtime::Compiler_Geometry == compType) {
            mTable[type] = c;
        } else if (Runtime::Compiler_Loop == compType) {
            mLoopTable[type] = c;
        }
    }
}    

   由代码可知,当类型为 Runtime::Compiler_Geometry 时注册到 mTable,否则注册到 mLoopTable 中。


   综上可见,扩展后的代码正是一个函数,其通过内部的 _create 函数注册到 mTable 或 mLoopTable 中,函数名 ___GeometryShape___create__ 呼应了 registerGeometryOps 函数中的调用。mTable 和 mLoopTable 呼应了 GeometryComputerManager::search 函数的实现。

1.1.1.1.1.2 GeometryComputer::onRecompute

    在函数 GeometryComputerUtils::shapeComputeAndGeometryTransform 中调用GeometryComputer::onRecompute (geo->onRecompute) 函数的代码如下:

// source/geometry/GeometryComputerUtils.cpp
ErrorCode GeometryComputerUtils::shapeComputeAndGeometryTransform(...) {
  // ...
    // Size Compute and compute Const
    for (int i=0; i<infos.size(); ++i) {
        auto& info = infos[i];
        // ...
    if (info.type == Schedule::CONSTANT) {
            // ...
            auto geo = GeometryComputer::search(info.op->type(), Runtime::Compiler_Loop);
            {
                auto res = geo->onRecompute(info.op, info.inputs, info.outputs, geoContext, tempBuffer);
                if (!res) {
                    // ...
                    res = geo->onCompute(info.op, info.inputs, info.outputs, geoContext, tempBuffer);
                }
                // ...
            }
            GeometryComputerUtils::makeRaster(tempBuffer, cmdBufferVir, ctx);
            for (auto t : info.outputs) {
                ctx.getRasterCacheCreateRecursive(t, cmdBufferVir);
            }
            // ...
        }
  } 
/** Geometry Transform */
    for (int i=0; i<infos.size(); ++i) {
        // ...
        auto geo = GeometryComputer::search(info.op->type(), compileType);
        {
            bool res = false;
            if (!tempBuffer.hasWrap) {
                res = geo->onRecompute(info.op, info.inputs, info.outputs, geoContext, tempBuffer);
            }
            if (!res) {
                // ...
                res = geo->onCompute(info.op, info.inputs, info.outputs, geoContext, tempBuffer);
            }
            // ...
            GeometryComputerUtils::makeRaster(tempBuffer, cmdBufferReal, geoContext);
            for (auto t : info.outputs) {
                auto des = TensorUtils::getDescribe(t);
                if (des->usage == Tensor::InsideDescribe::OUTPUT || des->usage == Tensor::InsideDescribe::TRAINABLE) {
                    // For output and trainable value, must directly compute the tensor
                    geoContext.getRasterCacheCreateRecursive(t, cmdBufferReal);
                }
            }
        }
    }    
    // ...  
}    

    GeometryComputer::search 函数找到对应的几何计算实现(如:GeometryShape),然后调用其方法 onRecompute。

    备注:GeometryComputer::onRecompute 调用是个多态,实际运行中根据 info.op->type() 类型,调用不同的几何计算子类。

    如下为 GeometryShape::onRecompute 的实现在其基类中,代码如下:

class GeometryComputer {
    virtual bool onRecompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs,
            Context& context, CommandBuffer& res) const override {
        return false;
    }
}    

1.1.1.1.1.3 GeometryComputer::onCompute

   在函数 GeometryComputerUtils::shapeComputeAndGeometryTransform 中调用 GeometryComputer::onCompute (geo->onCompute) 函数的代码详见。


   GeometryComputer::search 函数找到对应的几何计算实现(如:GeometryShape),然后调用其方法 onCompute。


   备注:GeometryComputer::onCompute 调用是个多态,实际运行中根据 info.op->type() 类型,调用不同的几何计算子类。


   如下为 GeometryShape::onCompute 的实现代码详见 。

1.1.1.1.1.4 GeometryComputerUtils::makeRaster

// source/geometry/GeometryComputerUtils.cpp
void GeometryComputerUtils::makeRaster(const CommandBuffer& srcBuffer, CommandBuffer& dstBuffer,
                                       GeometryComputer::Context& ctx) {
    dstBuffer.extras = srcBuffer.extras;
    for (int index = 0; index < srcBuffer.command.size(); ++index) {
        auto& iter = *srcBuffer.command[index];
        const Op* op = iter.op;
        auto& cmd     = iter;
        auto type = op->type();
        MNN_ASSERT(OpType_Raster != type);
        for (int i = 0; i < iter.inputs.size(); ++i) {
            if (!OpCommonUtils::opNeedContent(op, i)) {
                continue;
            }
            auto des = TensorUtils::getDescribe(cmd.inputs[i]);
            //MNN_ASSERT(des->tensorArrayAttr == nullptr);
            if (des->memoryType == Tensor::InsideDescribe::MEMORY_VIRTUAL) {
                ctx.getRasterCacheCreateRecursive(cmd.inputs[i], dstBuffer);
            }
        }
        dstBuffer.command.emplace_back(srcBuffer.command[index]);
    }
}


1.1.1.1.1.5 GeometryComputer::Context::getRasterCacheCreateRecursive

    在函数 GeometryComputerUtils::shapeComputeAndGeometryTransform 中调用

GeometryComputer::Context::getRasterCacheCreateRecursive 函数的代码如下:

ctx.getRasterCacheCreateRecursive(t, cmdBufferVir);

  其具体实现代码如下:

// source/geometry/GeometryComputer.cpp
void GeometryComputer::Context::getRasterCacheCreateRecursive(Tensor* src, CommandBuffer& cmd) {
    auto srcDes = TensorUtils::getDescribe(src);
    if (srcDes->memoryType != Tensor::InsideDescribe::MEMORY_VIRTUAL) {
        return;
    }

    if (_hasZeroDim(src)) {
        return;
    }
    for (auto& input : srcDes->regions) {
        MNN_ASSERT(input.origin != src);
        auto inputDes = TensorUtils::getDescribe(input.origin);
        while (inputDes->memoryType == Tensor::InsideDescribe::MEMORY_VIRTUAL) {
            if (1 != inputDes->regions.size()) {
                break;
            }
            bool merge = TensorUtils::fuseRegion(inputDes->regions[0], input);
            if (!merge) {
                break;
            }
            inputDes = TensorUtils::getDescribe(input.origin);
        }
        getRasterCacheCreateRecursive(input.origin, cmd);
    }
    getRasterCacheCreate(src, cmd);
}


目录
相关文章
|
机器学习/深度学习 算法 openCL
高效、轻量的深度学习框架MNN
MNN是一个高效、轻量的深度学习框架。
高效、轻量的深度学习框架MNN
|
3月前
|
人工智能 JavaScript API
从0到1,DeepSeek Harness保姆级安装与实操完整教程
2026年8月AI领域迎来一波密集更新浪潮,多款大模型与智能体框架集中对外发布。DeepSeek不仅更新V4 Pro正式版本,补齐Agent工具调用、链式任务执行与软件工程相关能力,还正式开源DeepSeek Harness智能体运行框架。该项目凭借“一切皆插件”的创新设计理念,上线之后快速收获大量开发者关注,短短数天GitHub Star突破15万,成为平台历史上增长速度最快的开源项目之一,也标志着国内大模型行业的竞争逻辑,逐步从单纯比拼模型调用价格,转向底层架构、插件生态与智能体执行能力的综合比拼。
3463 2
|
12月前
|
人工智能 程序员 API
GPT-5.2来了,老金详细给你说说它为什么是王
OpenAI悄然上线GPT-5.2,因谷歌Gemini 3发布引发“红色警报”。新模型提升显著:幻觉减少38%,上下文达40万token,支持长文档精准处理;ARC-AGI-2与GDPval评测显示其真实推理与工作能力大幅增强,尤其适合金融、法律等专业场景。推出Instant、Thinking、Pro三版本,满足不同需求。虽无惊艳发布,但聚焦打工人实际应用,标志着AI向通用生产力工具迈进。
1076 11
|
6月前
|
存储 监控 开发工具
阿里云日志服务SLS全流程对接与深度使用指南
本文是一篇详尽的阿里云日志服务SLS技术科普文章,从核心概念、服务开通、资源创建、数据采集、SDK集成、查询分析、可视化告警、安全权限到成本优化,全面讲解SLS的对接与使用。文章包含Logtail采集、Python/Java SDK代码示例、SPL与SQL查询等实操内容,帮助用户从零构建企业级日志管理平台,实现日志的统一归集、实时分析与智能运维。
|
11月前
|
JSON 人工智能 API
从对话到Agent:大模型工具调用能力的量化评测
大模型向Agent进化,工具调用是关键。本文介绍EvalScope评测框架,通过双重验证机制,量化评估模型“会不会用、能不能用好”工具,助力开发者打造可靠AI应用。
1297 4
|
人工智能 安全 Android开发
手机也能跑通义Qwen3大模型,手把手教你部署!
全球开源模型冠军Qwen3与端到端全模态模型Qwen2.5-Omni现已成功在手机上跑通!借助MNN支持,适配Android、iOS及桌面端,实现低延迟、本地化、高安全的AI体验。用户可通过自定义Sampler设置、System Prompt和Max New Tokens调节模型输出风格与长度。
7301 11
|
存储 缓存 物联网
MNN推理框架将大模型放进移动端设备,并达到SOTA推理性能!
随着移动端(手机/平板等)算力、内存、磁盘空间的不断增长,在移动端部署大模型逐渐成为可能。在端侧运行大模型,可以有一系列好处:去除网络延迟,加快响应速度;降低算力成本,便于大规模应用;不需数据上传,保护用户稳私。
3576 13
MNN推理框架将大模型放进移动端设备,并达到SOTA推理性能!
|
缓存 Web App开发 自然语言处理
关于解决chatGPT注册不了报错:chatGPT邮箱不支持
ChatGPT 开放了免费注册功能。然而,在用户创建过程中,一些人遇到了如下所示的提示信息:“Oops! The email you provided is not supported”,中文翻译为“糟糕,邮箱不支持”。
2160 4
|
存储 数据采集 运维
日志服务(SLS)测评
在本次测评中,我将对日志服务SLS产品进行全面评估,主要从以下四个方面展开。首先,我将进行功能测试,基于之前参加的两次训练实验,对其功能进行评估。其次,我将与其他数据分析&可观测性产品进行比较,以了解SLS的优势和差异。然后,我将进行成本与收益分析,探讨SLS作为一站式的可观测数据存储分析平台所带来的成本节约和收益提升。最后,我将对SLS进行简要总结,并提出一些期待,希望能够为用户提供有用的参考信息。
1319 58
|
搜索推荐 Python Windows
python中对于wordcloud词云生成报错提示的解决
通过搜索印象错误信息:ValueError:Only supported for TrueType fonts,几乎大部分人给出的选项都是让你指定TrueType fonts路径,或者新下载TTF字体,并重新指定,但是这两种解决方案并无法解决报错。 在真正解决问题之前,先来介绍几个与之相关的知识点,对于有经验的人,这样的知识点完全是“小菜”,但是对于初学者,这种知识点就是因为缺少相关实践而无从下手,无从搜索引擎。

热门文章

最新文章