How to build libtorch on mac arm?
Asked Answered
D

2

5

i downloaded libtorch and make these files on macbook pro ARM:

example-app/
     build/
     libtorch/
     CMakeLists.txt
     example-app.cpp

then i used these commands for build torch:

cmake -DCMAKE_PREFIX_PATH=/path-to-example-app/example-app/libtorch
make

and i get this error:

building for macOS-x86_64 but attempting to link with file built for unknown-arm64

can you help me?

Dimmick answered 6/1, 2021 at 9:24 Comment(0)
N
7

I was able to build libtorch library from source on my Mac M1 and run the C++ example-app project that you are looking at

(https://medium.com/@albertsundjaja/installing-pytorch-c-api-d52c722f47ec)

I did it with the following steps:

% git clone -b master --recurse-submodule https://github.com/pytorch/pytorch.git
% mkdir pytorch-build
% cd pytorch-build 
% cmake -DBUILD_SHARED_LIBS:BOOL=ON -DCMAKE_BUILD_TYPE:STRING=Release -DPYTHON_EXECUTABLE:PATH=`which python3` -DCMAKE_INSTALL_PREFIX:PATH=../pytorch-install ../pytorch

% cmake --build . --target install 

The above process creates a directory called pytorch-install. Copy files from the following directories in pytorch-install to respective directories in /example-app/libtorch/

bin
include
lib
share

Important Note: replace files not directories or some needed files from original libtorch will be lost.

Once I do this, I can run the following command per the tutorial:

% cmake -DCMAKE_PREFIX_PATH=/path-to-example-app/example-app/libtorch ..
    make

then running the command

% ./example-app

I get

 0.1816  0.6954  0.8272
 0.7898  0.0256  0.1385
[ CPUFloatType{2,3} ]
Nonreturnable answered 12/11, 2021 at 18:50 Comment(1)
For me I found that I can directly replace the entire libtorch directory with the newly created pytorch-install directory, so no need to replace files individually.Afebrile
F
1

Because libtorch build default only for x86 arch, not for arm arch. Probably you need to compile it for yourself.

I mean you the libtorch you download is pre-built library, which contains .so files. And this will not work, because pytorch only provide pre-build library for x86 architecture. And you are using an arm architecture cpu.

You need to download the libtorch source code, and build libtorch from scratch.

And after you build the libtorch from scratch, you will get binary file .so which is suitable to link on arm architecture cpu.

Frazzle answered 17/8, 2021 at 10:3 Comment(2)
This isn't really an answer. This should be a comment unless you know for sure this solution works. Also, his question shows that he is compiling it himself, so you should provide a more detailed explanation here.Chromaticity
Yes, you're probably right. But I think pytorch provide specific script to build libtorch from scratch, not like this.Frazzle

© 2022 - 2024 — McMap. All rights reserved.