#include <bits/stdc++.h>
using namespace std;
const int mo = 1e9 + 7;
long long add(long long x, long long y) {
  return x + y >= mo ? x + y - mo : x + y;
}
long long dec(long long x, long long y) { return x < y ? x - y + mo : x - y; }
long long quickmi(long long x, long long tim) {
  long long ret = 1;
  for (; tim; tim /= 2, x = x * x % mo)
    if (tim & 1) ret = ret * x % mo;
  return ret;
}
long long n, k, p;
struct func {
  long long k, b;
  func(const long long k_ = 0, const long long b_ = 0) {
    k = k_;
    b = b_;
  }
  friend func operator+(func a, func b) {
    return func(add(a.k, b.k), add(a.b, b.b));
  }
  friend func operator-(func a, func b) {
    return func(dec(a.k, b.k), dec(a.b, b.b));
  }
  friend func operator*(func a, func b) {
    return func(a.k * b.k % mo, (a.k * b.b + a.b) % mo);
  }
  func inv() {
    long long ny = quickmi(k, mo - 2);
    return func(ny, dec(0, b * ny % mo));
  }
  long long calc(long long x) { return (k * x + b) % mo; }
};
func operator^(func a, long long T) {
  func ret = func(1, 0);
  for (; T; T /= 2, a = a * a)
    if (T & 1) ret = ret * a;
  return ret;
}
long long gcd(long long x, long long y) { return !y ? x : gcd(y, x % y); }
pair<func, long long> calc(func f, long long x, long long tim) {
  if (tim == 1) return make_pair(f, x);
  pair<func, long long> u = calc(f, x, tim / 2);
  func fk = u.first;
  long long ret = u.second;
  ret = ((fk.k + 1) * ret + fk.b * (tim / 2)) % mo;
  fk = fk * fk;
  if (tim & 1) {
    ret = add(ret, fk.calc(x));
    fk = fk * f;
  }
  return make_pair(fk, ret);
}
void solve(long long n, long long k, func A, func B, long long &sum1,
           long long &sum2) {
  if (n == 1) {
    sum1 = A.b * quickmi(mo + 1 - A.k, mo - 2) % mo;
    sum2 = 0;
    return;
  }
  func a = A.inv(), b = B.inv();
  a = a ^ (n / k);
  solve(k, n % k, A * (a * b), a * b, sum1, sum2);
  long long tmp = sum2;
  sum2 = sum1;
  long long v1 = (func(A.k, A.b * (n % k) % mo) ^ (n / k)).calc(tmp);
  long long v2 = calc(func(A.k, A.b * k % mo), sum1, n / k).second;
  sum1 = add(v1, v2);
}
int main() {
  int _;
  cin >> _;
  for (; _; _--) {
    cin >> n >> k;
    p = (mo + 1) / 2;
    if (n == k) {
      printf("%I64d\n", quickmi(p, mo - 2));
      continue;
    }
    if (p == 1) {
      long long t = n / k;
      long long ret = (t * (t + 1) / 2 % mo * k % mo + n % k * (t + 1) % mo) %
                      mo * quickmi(n, mo - 2) % mo;
      printf("%I64d\n", ret);
      continue;
    }
    long long g = gcd(n, k);
    n /= g, k /= g;
    long long sum1, sum2;
    solve(n, k, func(1, 1), func(mo + 1 - p, 1), sum1, sum2);
    sum1 = sum1 * quickmi(n, mo - 2) % mo;
    printf("%I64d\n", sum1);
  }
  return 0;
}
