2018年12月8日土曜日

ubuntu で coredump が出ない

事の発端は、CentOS + PHP7.2 の環境で開発してたものをデモ用に流用して運用してたところから始まります。最初は、何の問題もなくちゃんと動作してたんですわ。yum update をしていて、途中から ERR_CONTENT_LENGTH_MISMATCH や ERR_INVALID_URL というの頻出するようになりまして、apache がアクセス不能になるという現象に悩まされはじめました。自分の作ってた php extension が悪いのかな?とか思って、色々と試してみたんですが、extension の module をロードしない状態でも、ERR_CONTENT_LENGTH_MISMATCH が起こるので、これはもう CentOS 固有の問題ではないかと考えはじめて、Ubuntu の環境で同じものを作ってみる決断を下しました。
まあ、自作の extension は CentOS + PHP7.2 で動作していたんですが、PHPもソースから入れようと、コンパイルしてみたら 自作 extension のコンパイルが通らなかったり…。もう一度、ソースを見直してみると、php5.x 系 php7.0 系 php7.1系 php7.2系 で構造もマクロも変わって互換性がほとんどない。この件に関しては後日、まとめようと考えております。

本題に入りまして、Ubuntu環境で動作させてみると、 ERR_CONTENT_LENGTH_MISMATCH が起きません。
が、Ubuntu 環境では、自作 php extension が SIGSEGV で落ちます。PHP_MINIT_FUNCTION のコードはログに記録されているのですが、何故か他の箇所のログが一切記録されないので、コアダンプを調べたいと思いました。
$ ulimit -c unlimted
を apache2 環境でするための機構があるらしいという事で、 /etc/default/apache2 というファイルに ulimit -c unlimited の1行を加えてみました。
 ulimit -c unlimited
コアダンプが出ない(#^ω^)ピキピキ

こんなの見つけた。
systemd時代に困らないためのlimits設定
(゚д゚)(。_。)(゚д゚)(。_。) ウンウン、そうだよねー怒り感じるよねー。
...
......
コアダンプが出ない...
  ( ⌒ )
   l | /
  ∧_∧
⊂(#・д・)
 /   ノ∪
 しー-J |l|
         人ペシッ!!
       __
       \  \
          ̄ ̄

見つけました。
Ubuntuでコアダンプが出力できないことがある
ふむふむ… /etc/default/apport を見てみると
# set this to 0 to disable apport, or to 1 to enable it
# you can temporarily override this with
# sudo service apport start force_start=1
enabled=1
なんで、enabled=0 に変更する。

やっと出ました。コアダンプ…。

あと、ログが出ない現象は、extension の MINIT 時には /var/log/php/error.log に出力されてるんですが、途中から /var/log/apache2/error.log に出力先が移動してました。
こんなん、わかるかーーーーー!
  ( ⌒ )
   l | /
  ∧_∧
⊂(#・д・)
 /   ノ∪
 しー-J |l|
         人ペシッ!!
       __
       \  \
          ̄ ̄

apache2 のコアダンプの設定は、[Linux] coreファイルについてに習い
/etc/systemd/system/apache2.service.d/override.conf
というファイルを作成して
[Service]
LimitCORE=infinity
と記述する事で落ち着きました

2018年8月22日水曜日

atlapp.h warning C4996: 'GetVersionExW': が古い形式として宣言されました。

WTL(Windows Template Library) を使用していて、ワーニングで怒られた。 以下のように修正を施す。
#if 1600 <= _MSC_VER
#include 
#endif

// Windows version helper
inline bool AtlIsOldWindows()
{
#if 1600 <= _MSC_VER
  return !IsWindowsVistaOrGreater();
#else
  OSVERSIONINFO ovi = { 0 };
  ovi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  BOOL bRet = ::GetVersionEx(&ovi);
  return (!bRet || !((ovi.dwMajorVersion >= 5) || (ovi.dwMajorVersion == 4 && ovi.dwMinorVersion >= 90)));
#endif
}

inline bool IsVista()
{
#if 1600 <= _MSC_VER
  return IsWindowsVistaOrGreater() && !IsWindows7OrGreater();
#else
  OSVERSIONINFO ovi = { sizeof(OSVERSIONINFO) };
  BOOL bRet = ::GetVersionEx(&ovi);
  return ((bRet != FALSE) && (ovi.dwMajorVersion >= 6));
#endif
}
ただし、WindowsSDK が古いと、VersionHelpers.h が含まれていないので、注意が必要。

2018年6月26日火曜日

Could not find com.android.tools.lint:lint-gradle:26.1.2 備忘録

Android Studio Gradle 系のトラブルが多い。

Could not find com.android.tools.lint:lint-gradle:26.1.2.

とかでエラーが出た場合は、プロジェクトの build.gradle を修正する

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'
    }
}

allprojects {
    repositories {
        // google 先生が追加されますた
        google()
        jcenter()
    }
}

追記: jcenter と google の位置関係は、google を先にした方が良いようです。
gradle:3.1.3 と記述している箇所は、どんどんバージョンが上がります。

2018年6月9日土曜日

boost::compute テスト

ちょいと GPU 使ってみようかと思って OpenCL について調べました。macbook pro retina MID2012 が壊れて、GPU が Intel Iris しか搭載されてないものに買い替えたため、Cuda は選択肢に無くなったんです。データセンターで使うな騒動もあったし、Cuda は、もうええんですわ。
そしたら、boost::compute というのがあって、OpenCL を使えるらしいのです。
チュートリアルを macbook pro でコンパイルしてみたら動く感じだったんで、本当に速いのかチェックしてみました。

コンパイルは、brew install boost してある状態で、こんなん。
g++ tutorial3.cpp -I /usr/include -framework OpenCL -std=c++11 -lboost_timer
チュートリアルを少し弄ってあります。
#include <vector>
#include <algorithm>

#include <boost/compute/algorithm/transform.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/functional/math.hpp>

#include <iostream>
#include <cmath>
#include <boost/timer/timer.hpp>

namespace compute = boost::compute;

int main()
{
    // get default device and setup context
    compute::device device = compute::system::default_device();
    compute::context context(device);
    compute::command_queue queue(context, device);

    std::vector<float> host_vector(100000000);

    boost::timer::cpu_timer timer;

    float n = 1.0f;
    std::generate(host_vector.begin(), host_vector.end(), [&n]() { return n += 1.0f; });
    // generate random data on the host
    //std::generate(host_vector.begin(), host_vector.end(), rand);

    timer.start();

    // create a vector on the device
    compute::vector<float> device_vector(host_vector.size(), context);

    // transfer data from the host to the device
    compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue );

    // calculate the square-root of each element in-place
    compute::transform(
        device_vector.begin(),
        device_vector.end(),
        device_vector.begin(),
        compute::sqrt<float>(),
        queue
    );

    // copy values back to the host
    compute::copy( device_vector.begin(), device_vector.end(), host_vector.begin(), queue );
    
    timer.stop();
    
    std::cout << "GPU: " << timer.format() << std::endl;

    n = 1.0f;
    std::generate(host_vector.begin(), host_vector.end(), [&n]() { return n += 1.0f; });
    
    std::sqrt<float>(n);
    
    timer.start();
    std::transform( host_vector.begin(), host_vector.end(), host_vector.begin(), static_cast<float (*)(float)>(std::sqrt));
    timer.stop();
    std::cout << "CPU: " << timer.format() << std::endl;
    
    //for( float x: host_vector) { std::cout << x << ","; }

    return 0;    
}
元は 10000 個の配列演算だったんですが、それだと
GPU:  0.078395s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (n/a%)
CPU:  0.000097s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (n/a%)
メモリ転送の処理に時間がかかって効果を確認できず。
100000000 個の配列演算で比較すると
GPU:  0.367576s wall, 0.000000s user + 0.170000s system = 0.170000s CPU (46.2%)
CPU:  0.819997s wall, 0.820000s user + 0.000000s system = 0.820000s CPU (100.0%)
ようやく効果が確認できました。

追記: host_vector size が 1000000000 -> 100000000 に訂正しました

2018年6月4日月曜日

Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'. 備忘録

どこかに書き留めないと、また調べる事になりそうなので、備忘録。

ある日突然、AndroidStudioでビルドをしようとすると、こんなメッセージが出てビルドできない。
Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

はい、compile は deprecated になり、implementation コマンドに変更されました。
以下のように書き換える必要があります。
dependencies {
    //compile files('../../Ref/Java/android-support-v4.jar')
    //compile 'com.android.support:support-v4:18.0.0'
    implementation 'com.android.support:support-v4:18.0.0'

    //compile files('../../Ref/Java/foo.jar')
    implementation fileTree(dir: '../../Ref/Java', include: 'foo.jar')
    //compile files('../../Ref/Java/bar.jar')
    implementation fileTree(dir: '../../Ref/Java', include: 'bar.jar')
}

2018年4月15日日曜日

tiny-dnn で遊ぼ (AutoEncoder)

#include "tiny_dnn/tiny_dnn.h"

namespace td = tiny_dnn;

#include "AudioFile.h"

#include <vector>
#include <random>

//Some traning variable 
const int SAMPLE_NUM = 1024;   //How much traning samples
const int WINDOW_SIZE = 2048;  //How long is each sample
const int BATCH_SIZE = 16;     //How many samples per batch
const int NUM_EPOCHS = 2048;   //How much epoch we want to run

int main()
{

  //Create a sample buffer
  std::vector<td::vec_t> samples(SAMPLE_NUM, td::vec_t(WINDOW_SIZE));

  AudioFile<float> audioFile;
  audioFile.load("a.wav"); //Load audio
  auto& data = audioFile.samples[0]; //Just use the first channel

  //Create a RNG and a distribution to generate random numbers
  std::mt19937 rng;
  std::uniform_int_distribution<int> dist(0, data.size()-WINDOW_SIZE);
  //Generate samples
  for(auto& v : samples)
  {
    int offset = dist(rng);//Generate random offsets
    auto start = data.begin() + offset;
    //Copy data from source to sample
    std::copy(start, start+WINDOW_SIZE, v.begin());
  }
  
  //Create an autoencoder
  td::network<td::sequential> net;
  net << td::fully_connected_layer(WINDOW_SIZE, 512) << td::tanh_layer()
    << td::fully_connected_layer(512, WINDOW_SIZE);
  
  //Helper class
  td::progress_display disp(SAMPLE_NUM);
  td::timer t;
  
  int currentEpoch = 0;
  
  //Callbacks when a mini bactch is done
  auto onMinibatch = [&]()
  {
    //This updates the progress display
    disp += BATCH_SIZE;  
  };
  
  //Callbacks when an epoch is done
  auto onEpoch = [&]()
  {
    std::cout << "Epoch " << ++currentEpoch << "/" << NUM_EPOCHS << "done. "
      << t.elapsed() << "s elapsed." << std::endl;
      
    //Reset progress display and timer
    disp.restart(SAMPLE_NUM);
    t.restart();
  };
  
  //train the network with absolute(L1) error.
  td::adagrad optimizer;
  net.fit<td::absolute>(optimizer, samples, samples, BATCH_SIZE, NUM_EPOCHS
    , onMinibatch, onEpoch);
  net.save("net");

  //Let's try the network
  std::vector<float> result(data.size());
  for(int i=0;i<data.size();i+=WINDOW_SIZE)
  {
    //Input to the neural network
    td::vec_t input(WINDOW_SIZE);
    //copy data into the input vector
    std::copy(data.begin()+i, data.begin()+i+WINDOW_SIZE, input.begin());

    //Run the neural network then copy it to the result buffer
    td::vec_t predict = net.predict(input);
    std::copy(result.begin()+i, result.begin()+i+WINDOW_SIZE, predict.begin());
  }
  
  //Save the audio we ganarated
  AudioFile<float> saveFile;
  AudioFile<float>::AudioBuffer buffer(1);
  buffer[0] = result;
  audioFile.setAudioBuffer(buffer);
  audioFile.save("audioFile2.wav");
}
コンパイル
g++ auto_encoder.cpp -I . -std=c++14 AudioFile.cpp
実行
...

0%   10   20   30   40   50   60   70   80   90   100%
|----|----|----|----|----|----|----|----|----|----|
***************************************************
Epoch 336/2048done. 40.7405s elapsed.

0%   10   20   30   40   50   60   70   80   90   100%
|----|----|----|----|----|----|----|----|----|----|
***************************************************
Epoch 337/2048done. 42.2788s elapsed.

...
wavファイルによると思うが、3日ぐらいかかりそうな勢い

tiny-dnn で遊ぼ (XOR)

チュートリアル XOR
#include <tiny_dnn/tiny_dnn.h>
#include <vector>

namespace td = tiny_dnn;
namespace tda = tiny_dnn::activation;

int main() {
  td::network<td::sequential> net;
  net << td::fully_connected_layer(2,3) << td::sigmoid_layer()
  << td::fully_connected_layer(3,1) << td::sigmoid_layer();

  std::vector<td::vec_t> trainIn = {{0,0}, {0,1}, {1,0}, {1,1}};
  std::vector<td::vec_t> trainOut = {{0}, {1}, {1}, {0}};

  td::gradient_descent optimizer; //(0.53);
  optimizer.alpha = 0.53f;
  net.fit<td::mse>(optimizer, trainIn, trainOut, 1, 1000);
  net.save("net");
  std::cout << net.predict({0,0})[0] << std::endl;
  std::cout << net.predict({0,1})[0] << std::endl;
  std::cout << net.predict({1,0})[0] << std::endl;
  std::cout << net.predict({1,1})[0] << std::endl;

  return 0;
}
出力
0.0411867
0.956243
0.959534
0.037655